簡體   English   中英

使用JOIN包含NULL值

[英]Using JOIN to include NULL values

我的目標是合並來自兩個表(預測和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

我需要幫助 :)

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM