简体   繁体   English

返回所有父表行,但对于与WHERE子句与MYSQL不匹配的子表行返回null

[英]Returning all parent table rows but return null for child table rows that don't match the WHERE clause with MYSQL

Hi there I'm stuck on a problem with a personal website I'm building. 嗨,我在建立个人网站时遇到了问题。 The page is a user's dashboard that has a list of all the classes on the system. 该页面是用户的仪表板,其中包含系统上所有类的列表。 That table is called 'classes' and it is the parent table of 'class_reponses' which is a table that records if the user has either started, finished or failed to finish the class. 该表称为“类”,它是“ class_reponses”的父表,该表记录用户是否已开始,完成或未能完成该类。 'class_responses' has a user_id in it. 'class_responses'中有一个user_id。 I'm trying to build a query that will list all of classes rows and simply have null fields when class_reponses user_id does not match the given id. 我正在尝试建立一个查询,该查询将列出所有类行,并且当class_reponses user_id与给定的id不匹配时仅具有空字段。

SELECT * FROM classes AS Class
LEFT JOIN class_responses AS ClassResponse
ON Class.id = ClassResponse.class_id
WHERE ClassResponse.user_id = 7

This query is something similar to what I'm trying to make, but if classes has no child class_responses that match the user_id then the classes row won't show up. 该查询与我要进行的查询类似,但是如果类没有与user_id匹配的子类class_responses,则不会显示“类”行。

Put the conditions on a left joined table in the ON clause. 将条件放在ON子句中的左连接表上。

SELECT * FROM classes AS c
LEFT JOIN class_responses AS cr
ON c.id = cr.class_id and cr.user_id = 7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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