SQL查询以查找另一列中不存在ID的位置

时间:2018-03-16 03:14:56

标签: mysql sql sql-server tsql

我有一张桌子:帐户

+-----------+-----------------+------+
| AccountNo | ParentAccountNo | name |
+-----------+-----------------+------+
|         1 | null            | ABC  |
|         2 | 1               | ABCD |
|         3 | 1               | CDE  |
|         4 | 2               | DEF  |
|         5 | null            | GHI  |
|         6 | 3               | MNO  |
|         7 | 5               | JKL  |
+-----------+-----------------+------+

我需要获得AccountNo中不存在ParentAccountNo的结果。

例如,根据上述数据,我期望的结果是:

+-----------+-----------------+------+
| AccountNo | ParentAccountNo | name |
+-----------+-----------------+------+
|         4 |               2 | DEF  |
|         6 |               3 | MNO  |
|         7 |               5 | JKL  |
+-----------+-----------------+------+

接受MySQLSQL-Server的答案。

1 个答案:

答案 0 :(得分:4)

通过LEFT JOIN = AccountNo上的ParentAccountNo将表格与自身相关联,您可以过滤掉没有匹配ID&#39的行; S

WITH Accounts AS(
    SELECT *
    FROM (VALUES (1,null,'ABC'),
                 (2,1,'ABCD'),
                 (3,1,'CDE'),
                 (4,2,'DEF'),
                 (5,null,'GHI'),
                 (6,3,'MNO'),
                 (7,5,'JKL')) V(AccountNo,ParentAccountNo,name))


SELECT t1.* 
FROM Accounts t1
LEFT JOIN Accounts t2 ON t1.AccountNo = t2.ParentAccountNo
WHERE t2.AccountNo IS NULL

enter image description here

[DEMO HERE]

您对WITH的使用感到好奇。 。

这相当于我对WITH的简写用法:

CREATE TABLE Accounts (
    AccountNo INT NOT NULL,
    ParentAccountNo INT NULL,
    Name VARCHAR(200))

INSERT INTO Accounts
    SELECT *
    FROM (VALUES (1,null,'ABC'),
                 (2,1,'ABCD'),
                 (3,1,'CDE'),
                 (4,2,'DEF'),
                 (5,null,'GHI'),
                 (6,3,'MNO'),
                 (7,5,'JKL')) V(AccountNo,ParentAccountNo,name)