首页 > 解决方案 > 列出 table1 中的所有项目并填写 table2 中匹配的信息

问题描述

我需要列出表 1 中的所有项目并显示表 2 中的匹配记录。表 1 包含 6 行和类别。表 2 包含用户和匹配的类别。一些用户可以属于多个类别,因此可以在此表中出现多次。

这就是我的表格的样子:

表格1:

- catID
- categoryname

表 2:

- userID
- catID
- catDetails

我已经尝试过加入、联合……并以下面的查询结束。

SELECT * FROM table1 one , table2 two
WHERE two.userID = 1  AND one.catID = two.catID

我期待类似的东西:

catID1 - userID1
catID2
catID3 - userID1
catID4 - userID1 - catdetails1
catID4 - userID1 - catdetails2
catID4 - userID1 - catdetails3
catID4 - userID1 - catdetails4
catID5

(用户有 1 和 3 一次,以及 4x4)

但我得到:

catID1 - userID1
catID3 - userID1
catID4 - userID1 - catdetails1
catID4 - userID1 - catdetails2
catID4 - userID1 - catdetails3
catID4 - userID1 - catdetails4

catID2 和 catID5 未按需要显示。

即使所选用户没有匹配的数据,如何确保所有类别都可见?

标签: mysqlsqljoin

解决方案


您可以使用LEFT JOIN,

LEFT JOIN 关键字返回左表 (table1) 中的所有记录,以及右表 (table2) 中的匹配记录。如果没有匹配,则右侧的结果为 NULL。

在此处输入图像描述

SELECT * FROM table1 one 
LEFT JOIN table2 two
ON one.catID = two.catID
AND two.userID = 1

演示:

http://sqlfiddle.com/#!9/313798/4

输出

catID   categoryname    userID  catID   catDetails
1       CAT1            1       1       (null)
2       CAT2            (null)  (null)  (null)
3       CAT3            1       3       (null)
4       CAT4            1       4       catdetails2
4       CAT4            1       4       catdetails3
4       CAT4            1       4       catdetails4
4       CAT4            1       4       catdetails1
5       CAT5            (null)  (null)  (null)

推荐阅读