mysql - 我的连接表中的某些结果为 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 字段的存储方式完全相同,tags
但tags
显示其值,而其他字段为 NULL,为什么?
此外,所有字段都不是列名,它们是别名,因为它们都存储为value
与field_id
我需要检索所有数据,并且只LIKE %%
在tags
.
解决方案
你说只有标签应该包含'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
推荐阅读
- amazon-web-services - 由于 CORS 错误,AWS S3 未与 API Gateway 连接
- windows - 如何从 .bat 文件运行多个服务
- amazon-web-services - 443 以外端口的 AWS 虚拟机 Https
- java - 在 Java 中调用子类的方法而不进行向下转换
- c# - 控制台应用程序中的工厂设计模式实现
- c++ - 发布模式下的 Xcode 无法编译
- 抱怨 __builtin_ia32_emms() - python - 如何根据确切的查询集过滤 Django ManyToManyField?
- visual-studio-code - 如何配置运行/调试栏任务?
- python-3.x - Django Rest框架获取父对象中的所有外键数据
- ftp - 在 Mule API 中使用 FTP/SFTP 连接器时获取 MULE:SOURCE_RESPONSE_SEND