mysql - 列出 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 未按需要显示。
即使所选用户没有匹配的数据,如何确保所有类别都可见?
解决方案
您可以使用LEFT JOIN,
LEFT JOIN 关键字返回左表 (table1) 中的所有记录,以及右表 (table2) 中的匹配记录。如果没有匹配,则右侧的结果为 NULL。
SELECT * FROM table1 one
LEFT JOIN table2 two
ON one.catID = two.catID
AND two.userID = 1
演示:
输出
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)
推荐阅读
- android - 尝试安装 Cordova Android Platform 9 并以 Android API 29 为目标时出现错误“无法从平台加载 PlatformApi”
- spring-boot - springboot中只为oauth2实现客户端需要哪些组件和属性?
- python - 更新数据表实时 Python/Dash
- google-colaboratory - Google Colab:运行时断开连接
- html - 无法通过调用 api 请求以角度将 dataSource 值输出到表中
- python - O(n^2) 是否意味着算法会抛出 n^2 次循环?
- c++ - OpenCV stereosgbm 代码 - 未解析的外部符号
- javascript - 在 Grunt 中使用 minPrepare 引发 pattern.indexOf 错误
- java - 在java中读取webp图像
- css - 使用 tailwind 和 bulma css 运行 gulp 任务时丢失分号错误