简体   繁体   English

如果连接表中没有匹配项,如何仍然从连接查询中的表中获取数据

[英]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_contentsnm_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_idfield_idvalue

the field id of snm_content is the same as the field item_id of snm_fields_values . snm_content的字段idsnm_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_idsnm_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_contentid不存在item_idsnm_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM