简体   繁体   English

使用JOIN包含NULL值

[英]Using JOIN to include NULL values

My goal to combine results from two tables (predictions and user_score) so that I have all users who scored the points in the match and who did not score the points, but are participating in the pool (poolid=110) 我的目标是合并来自两个表(预测和user_score)的结果,以便让所有在比赛中获得得分但未得分的用户都参与其中(poolid = 110)

predictions 预测

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

user_score user_score

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

Results should be like that: 结果应该是这样的:

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

This is few queries that i tried: 这是我尝试过的几个查询:

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

This query doesnt work on my SQL version Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/5.6.31 / Database client version: libmysql - mysqlnd 5.0.11-dev - 20120503 / 此查询不适用于我的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

I need help :) 我需要帮助 :)

Use a LEFT JOIN, and put the condition matchid = 121 into the ON clause: 使用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

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

You can also use your RIGHT JOIN method, but the matchid = 121 condition must be in the ON clause. 您也可以使用RIGHT JOIN方法,但是matchid = 121条件必须在ON子句中。

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

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

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