SQL:在表2上使用左连接时返回表2中的列为空

时间:2014-09-30 15:06:16

标签: sql join

我尝试从第二个表中找不到值列表的左连接返回结果,但我需要我的结果才能明确返回未找到哪个值。我认为类似下面的东西会起作用,但是当然table2是null,所以我不能从中拉出一列。

select table1.pidm, column1, column2, **column3** from
(select pidm, column1, column2 from aaa) table1
left join
(select pidm, column3 from bbb where **column3** in ('X','Y','Z')) table 2
on table1.pidm=table2.pidm where **table2.pidm is null**;

我可能忽略了另一种更简单的方法,但我无法弄清楚它是什么!

3 个答案:

答案 0 :(得分:1)

如果两个表的表结构完全相同,您可以尝试:

select * from Table1

except

select * from Table2

如果它们不同,您可以在SELECT子句中选择所需的确切列

答案 1 :(得分:0)

select table1.pidm, x.CountX, y.CountY, z.CountZ 
from table1
left join
(select pidm, count(*) CountX from bbb where column3 = 'X' group by pidm) x on x.pidm = table1.pidm
 left join
(select pidm, count(*) CountY from bbb where column3 = 'Y' group by pidm) y on y.pidm = table1.pidm
left join
(select pidm, count(*) CountZ from bbb where column3 = 'Z' group by pidm) x on z.pidm = table1.pidm

这将为您提供table1中的所有pidm,以及相关的X,Y和Z值的计数。 如果您只想要丢失X,Y或Z中的一个的pidm,请添加:

where x.CountX = 0 or y.CountY = 0 or z.CountZ = 0

(编辑为按照pidm'添加')

答案 2 :(得分:0)

您的查询将仅选择来自aaa的条目,其中bbb不包含同一pidm的任何行(column3不是'X'之一的行除外) ,'Y'或'Z')。如果您需要查看缺少哪些条目,我会看到两种常规方法。让我们看一下这个数据集:

CREATE TABLE `aaa` (`pidm` BIGINT PRIMARY KEY AUTO_INCREMENT, `column1` VARCHAR(10), `column2` VARCHAR(10));
INSERT INTO `aaa` (`pidm`, `column1`, `column2`)
VALUES (1, '1a', '1b'), (2, '2a', '2b'), (3, '3a', '3b'), (4, '4a', '4b'), (5, '5a', '5b'), (6, '6a', '6b'),
  (7, '7a', '7b'), (8, '8a', '8b');
CREATE TABLE `bbb` (`pidm` BIGINT, `column3` VARCHAR(10));
INSERT INTO `bbb` (`pidm`, `column3`)
VALUES (1, 'X'), (1, 'Y'), (1, 'Z'), (2, 'Y'), (2, 'Z'), (3, 'X'), (3, 'Z'), (4, 'Z'), (5, 'X'), (5, 'Y'), (6, 'Y'),
  (7, 'X');

加入一个只包含'X','Y'和'Z'的“桌子”

SELECT
  table1.pidm,
  table1.column1,
  table1.column2,
  temp1.column3
FROM
  aaa AS table1
  JOIN (SELECT
          'X' AS column3
        UNION SELECT
                'Y'
        UNION SELECT
                'Z') temp1
  LEFT JOIN
  bbb AS table2 ON table2.pidm = table1.pidm AND table2.column3 = temp1.column3
WHERE table2.pidm IS NULL;

这将产生12行,其中结果中column3的每个值将代表pidmbbb中找不到行SELECT table1.pidm, table1.column1, table1.column2, COALESCE(SUM(table2.column3 = 'X'), 0) AS X, COALESCE(SUM(table2.column3 = 'Y'), 0) AS Y, COALESCE(SUM(table2.column3 = 'Z'), 0) AS Z FROM aaa AS table1 LEFT JOIN bbb AS table2 ON table2.pidm = table1.pidm GROUP BY table1.pidm; 。您当然可以将此作为子查询使用,并创建类似于2的结果。

直接计算值

column3

这将产生8行,其中pidm的每个aaa值的计数附加到{{1}}的数据。