首页 > 解决方案 > 我的连接表中的某些结果为 NULL,为什么会这样?

问题描述

我有一个查询来搜索公司。每个公司都有一些存储在另一个表中的属性。

发布到我的查询和人们搜索的值称为tags.

这是我的查询:

SELECT cnt.id as content_id, cnt.title as content_title, cnt.featured, cnt.ordering, cnt.alias as content_alias, cnt.catid, cnt.images, cnt.state, cnt.introtext,
MAX(case when f.field_id = 7 then f.value end) as hoofdafbeelding,
MAX(case when f.field_id = 8 then f.value end) as openingstijden,
MAX(case when f.field_id = 9 then f.value end) as straat,
MAX(case when f.field_id = 10 then f.value end) as facebook,
MAX(case when f.field_id = 11 then f.value end) as instagram,
MAX(case when f.field_id = 12 then f.value end) as telefoonnummer,
MAX(case when f.field_id = 13 then f.value end) as website,
MAX(case when f.field_id = 16 then f.value end) as tags
FROM snm_content cnt
LEFT JOIN snm_fields_values f
ON cnt.id = f.item_id
WHERE f.value LIKE '%vlees%'
GROUP BY cnt.id, cnt.title, cnt.featured, cnt.alias, cnt.catid, cnt.images, cnt.state, cnt.introtext
ORDER BY cnt.ordering

我的问题是在我的结果中所有字​​段(带有 MAX 的行)都是 NULL,除了标签。这是为什么?

上面的查询给了我这个结果:

在此处输入图像描述

所有 NULL 字段的存储方式完全相同,tagstags显示其值,而其他字段为 NULL,为什么?

此外,所有字段都不是列名,它们是别名,因为它们都存储为valuefield_id

我需要检索所有数据,并且只LIKE %%tags.

标签: mysqlsqldatabase

解决方案


你说只有标签应该包含'vlees'值。所以,你不应该把它放在 WHERE 因为它过滤整个查询而不是只过滤标签。我已更新您的查询,更改了“vlees”过滤器的位置。如果其他字段(hoofdafbeelding,openingstijden..)应该有另一个过滤器,你应该像我更新的标签一样过滤它们。最后一件事,我认为 f.field_id=? 过滤器也不正确。使用此过滤器,您的结果 CASE 仅适用于一个 content.id,您可能应该删除它们。

SELECT
    cnt.id AS content_id
   ,cnt.title AS content_title
   ,cnt.featured
   ,cnt.ordering
   ,cnt.alias AS content_alias
   ,cnt.catid
   ,cnt.images
   ,cnt.state
   ,cnt.introtext
   ,MAX(CASE WHEN f.field_id = 7   THEN f.value END) AS hoofdafbeelding
   ,MAX(CASE WHEN f.field_id = 8   THEN f.value END) AS openingstijden
   ,MAX(CASE WHEN f.field_id = 9   THEN f.value END) AS straat
   ,MAX(CASE WHEN f.field_id = 10  THEN f.value END) AS facebook
   ,MAX(CASE WHEN f.field_id = 11  THEN f.value END) AS instagram
   ,MAX(CASE WHEN f.field_id = 12  THEN f.value END) AS telefoonnummer
   ,MAX(CASE WHEN f.field_id = 13  THEN f.value END) AS website
   ,MAX(CASE WHEN f.field_id = 16  THEN f.value END) AS tags
FROM snm_content cnt
LEFT JOIN snm_fields_values f ON cnt.id = f.item_id
WHERE EXISTS (SELECT 1 FROM snm_fields_values SFV WHERE cnt.id = SFV.item_id AND  SFV.value LIKE '%vlees%')
GROUP BY cnt.id
        ,cnt.title
        ,cnt.featured
        ,cnt.alias
        ,cnt.catid
        ,cnt.images
        ,cnt.state
        ,cnt.introtext
ORDER BY cnt.ordering

推荐阅读