[英]How to still get data from a table in a join query if there is nothing to match in the joined table
I have a database which contains two tables,我有一个包含两个表的数据库,
snm_content
and snm_fields_values
snm_content
和snm_fields_values
snm_content
has numerous fields, only id
is relevant here, and snm_fields_values
has three fields, item_id
, field_id
and value
snm_content
有很多字段,这里只有id
是相关的,而snm_fields_values
有三个字段, item_id
, field_id
和value
the field id
of snm_content
is the same as the field item_id
of snm_fields_values
. snm_content
的字段id
与snm_content
的字段item_id
snm_fields_values
。
I want to get all data from snm_content
and join snm_fields_values
but also retrieve data from snm_content
if nothing can be joined.我想从
snm_content
获取所有数据并加入snm_fields_values
但如果没有任何东西可以加入,也从snm_content
检索数据。 So if there is no matching item_id
in snm_fields_values
then still get the data from snm_content
.因此,如果
snm_fields_values
没有匹配的item_id
,则仍然从snm_content
获取数据。
The problem is with the following query I only get results from snm_content
if there is a matching item_id
in snm_fields_values
问题是与下面的查询我只能从结果
snm_content
如果有匹配item_id
在snm_fields_values
SELECT cnt.*,
MAX(case when f.field_id = 4 then f.value end) as service_icon
FROM snm_fields_values f
JOIN snm_content cnt
ON cnt.id = f.item_id
WHERE cnt.catid = 9
AND cnt.state = 1
ORDER BY cnt.ordering
If no item_id
exists for an id
in snm_content
nothing is retrieved from snm_content
.如果
snm_content
的id
不存在item_id
, snm_content
不会从snm_content
检索任何snm_content
。 How can I fix that?我该如何解决? I've tried switching the order of retrieving data but this had the same result.
我试过切换检索数据的顺序,但这有相同的结果。
Use a left join
:使用
left join
:
SELECT cnt.*,
MAX(case when f.field_id = 4 then f.value end) as service_icon
FROM snm_content cnt LEFT JOIN
snm_fields_values f
ON cnt.id = f.item_id
WHERE cnt.catid = 9 AND cnt.state = 1
GROUP BY cnt.id
ORDER BY cnt.ordering;
Note that this adds GROUP BY
so you get one row per group in the content table.请注意,这会添加
GROUP BY
因此您在内容表中每组获得一行。
You can also use a correlated subquery:您还可以使用相关子查询:
SELECT cnt.*,
(SELECT MAX(case when f.field_id = 4 then f.value end)
FROM snm_fields_values f
WHERE cnt.id = f.item_id
) as service_icon
FROM snm_content cnt
WHERE cnt.catid = 9 AND cnt.state = 1
GROUP BY cnt.id
ORDER BY cnt.ordering;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.