【问题标题】:Using JOIN to include NULL values使用 JOIN 包含 NULL 值
【发布时间】:2018-01-14 18:21:03
【问题描述】:

我的目标是结合两个表(predictions 和 user_score)的结果,这样我就拥有了所有在比赛中得分和没有得分但正在参与池的用户 (poolid=110)

预测

predid    | matchid  | ueserid    | points |
--------------------------------------------
1            121            8        1
2            122            8        2
3            122            10       3

user_score

id    | poolid  | userid    | 
------------------------------
1         110            8
2         110            10
3         111            8
4         111            10

结果应该是这样的:

| matchid  | ueserid    | points |  poolid 
--------------------------------------------
  121            8          1      110
  null           10         null   110

这是我尝试过的几个查询:

SELECT * FROM predictions LEFT JOIN user_score on predictions.userid = user_score.userid WHERE predictions.matchid=121 and user_score.poolid=110

SELECT * FROM predictions RIGHT JOIN user_score on predictions.userid = user_score.userid WHERE predictions.matchid=121 and user_score.poolid=110

此查询不适用于我的 SQL 版本 Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/5.6.31 / 数据库客户端版本:libmysql - mysqlnd 5.0.11-dev - 20120503 /

SELECT * FROM predictions FULL OUTER JOIN user_score on predictions.userid = user_score.userid WHERE predictions.matchid=121 and user_score.poolid=110

我需要帮助:)

【问题讨论】:

  • MySQL 不支持 FULL OUTER JOIN

标签: php mysql


【解决方案1】:

使用 LEFT JOIN,并将条件 matchid = 121 放入 ON 子句:

select p.matchid, s.userid, p.points, s.poolid 
from user_score s
left join predictions p
  on  p.userid  = s.userid
  and p.matchid = 121
where s.poolid = 110

演示:http://sqlfiddle.com/#!9/2a1a5/1

您也可以使用 RIGHT JOIN 方法,但 matchid = 121 条件必须在 ON 子句中。

http://sqlfiddle.com/#!9/2a1a5/6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 2016-05-11
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多