如何使用NULL值将表与自身连接起来

时间:2014-04-21 06:19:18

标签: mysql sql join

我有这张表(测试):

+----+---------+-----+---+
| ID |  Name   |  A  | B |
+----+---------+-----+---+
|  1 | Steve   | 200 | 0 |
|  2 | Steve   | 200 | 1 |
|  5 | James   |  90 | 0 |
|  4 | James   |  50 | 1 |
|  3 | Warrick | 100 | 1 |
+----+---------+-----+---+

和这个SQL查询:

SELECT one.Name as Name, one.A as one_value, zero.A as zero_value 
FROM test one LEFT JOIN test zero ON one.Name = zero.Name AND one.A <> zero.A
WHERE zero.B = 0 AND one.B = 1

返回:

+-------+-----------+------------+
| Name  | one_value | zero_value |
+-------+-----------+------------+
| James |        50 |         90 |
+-------+-----------+------------+

但我想要的是当记录只存在于B = 1时,它包含在具有NULL值的响应中,或者在zero_value列中,如下所示:

+---------+-----------+------------+
|  Name   | one_value | zero_value |
+---------+-----------+------------+
| James   |        50 | 90         |
| Warrick |       100 | NULL       |
+---------+-----------+------------+

我该怎么做?

编辑:

我解决了这个问题:

SELECT one.Name, one.A, zero.A
FROM test one LEFT JOIN test zero ON one.Name = zero.Name AND ( zero.B = 0 OR zero.B is NULL )
WHERE ( one.A <> zero.A OR zero.A is null )

4 个答案:

答案 0 :(得分:2)

由于左连接,zero.B的值可能为NULL,因此您需要扩展WHERE条件:

WHERE one.B=1 AND (zero.B IS NULL OR zero.B = 0)

更新

您还应该将得分条件下移到WHERE:

WHERE one.B=1 AND (zero.B IS NULL OR zero.B = 0)
    AND (zero.A IS NULL OR one.A <> zero.A)

答案 1 :(得分:0)

这个怎么样

select Name ,
       (case when B= 0 Then A else null) as zero_value,
       (case when B= 1 Then A else null) as one_value
from test

答案 2 :(得分:0)

LEFT JOIN在这里是件好事,这就是你想要的:

SELECT
    one.Name
    ,one.A as one_value
    , zero.A as zero_value 
FROM test one
    LEFT JOIN test zero
        on one.Name = zero.Name
        and zero.B = 0
where one.B = 1

也许你想要处理记录只存在于B = 0时它是否同时包含在one_value列中具有NULL值的响应中:

SELECT
   test.Name
   , one.A as one_value
   , zero.A as zero_value 
FROM 
    (   SELECT Name
        FROM test
        GROUP BY Name) test
    LEFT JOIN test one
        on test.Name = one.Name
        and one.B = 1
    LEFT JOIN test zero
        on test.Name = zero.Name
        and zero.B = 0

Here is a demo for both queries :)

答案 3 :(得分:0)

http://www.sqlfiddle.com/#!2/6332a/7/0

尝试为u

提供精确结果的thiz查询

SELECT Test.nme, one.A AS one_value, zero.A AS zero_value FROM(SELECT name AS nme FROM test WHERE name NOT in( SELECT one.Name FROM test one LEFT JOIN test zero ON (one.Name = zero.Name AND one.A=zero.A) WHERE zero.B=0 AND one.B=1)GROUP BY name)Test LEFT JOIN test one ON test.nme=one.Name AND one.B=1 LEFT JOIN test zero ON test.nme=zero.Name AND zero.B=0;