简体   繁体   English

MySQL LEFT JOIN在第二个表中带有可选值

[英]MySQL LEFT JOIN with optional value in second table

I have two tables: projects and user_licenses . 我有两个表: projectsuser_licenses

I'd like to grab the entire list of projects from the database, as well as the user's current license state. 我想从数据库中获取整个项目列表,以及用户当前的许可证状态。 The licenses table has a user ID field which I check against a $_SESSION variable for the value. 许可证表有一个用户ID字段,我根据$_SESSION变量检查该值。 The thing is, they might not have a license, or a non-logged in visitor may want to see the projects list. 问题是,他们可能没有许可证,或者未登录的访问者可能希望查看项目列表。 My question is this: How can I get the data from the left table always display, but only grab data for that row from the right table when certain conditions are met? 我的问题是:如何始终显示左表中的数据,但只有在满足某些条件时才从右表中获取该行的数据?

The query I have at the moment is this: 我目前的查询是这样的:

   SELECT Projects.*, 
          UserLicenses.* 
     FROM Projects 
LEFT JOIN UserLicenses ON Projects.id = UserLicenses.project_id 
    WHERE UserLicenses.user_id = 12 
 ORDER BY name ASC

Add any extra conditions to the on clause of the left join. 将任何额外条件添加到左连接的on子句中。 They will only affect the joined table. 它们只会影响连接表。

  SELECT Projects.*, 
          UserLicenses.* 
     FROM Projects 
LEFT JOIN UserLicenses 
       ON Projects.id = UserLicenses.project_id 
          and UserLicenses.user_id = 12 
          and UserLicences.Question = '6*7'
          and UserLicences.Answer = 42
 ORDER BY name ASC

This will return projects without matching licenses. 这将返回没有匹配许可证的项目。

Move the UserLicenses condition away from WHERE, and up to the JOIN condition. 将UserLicenses条件从WHERE移开,直到JOIN条件。 By having it in the WHERE part, you will never see those "left" rows because they are filtered away. 通过将它放在WHERE部分中,您将永远不会看到那些“左”行,因为它们被过滤掉了。

You can also probably use WHERE (UserLicenses.user_id = 12 OR UserLicenses.user_id IS NULL) Don't do that. 您也可以使用 WHERE (UserLicenses.user_id = 12 OR UserLicenses.user_id IS NULL) 不要这样做。 Just move it to the join condition like this: 只需将其移动到连接条件,如下所示:

LEFT JOIN UserLicenses ON (Projects.id = UserLicenses.project_id AND UserLicenses.user_id = 12)

You can use LEFT JOIN 你可以使用LEFT JOIN

If its conditions match then values show otherwise null value shows. 如果其条件匹配,则值显示否则显示空值。

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

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