查找缺少的设置

时间:2019-03-30 06:09:19

标签: sql-server-2012

我的数据库中有两个表。表A是信息数据表,表B是设置表。如何找到表A缺少表B中的一项设置。

E.G。

Table A
username       setting
Mark           1
Mark           2
Martin         2
Jane           1

Table B
Possible_Setting
1             
2             
3

Result Table
username      missing_setting
Mark          3
Martin        1
Martin        3
Jane          2
Jane          3

感谢帮助!

1 个答案:

答案 0 :(得分:0)

由于交叉联接,如果表的大小很大,这可能效率不高,但这是我唯一能想到的答案。

    SELECT a.username, b.Possible_Setting AS missing_setting 
FROM 
    (SELECT DISTINCT username FROM TableA a) a 
    CROSS JOIN TableB b 
WHERE 
    NOT EXISTS (
        SELECT * 
        FROM TableA real_a 
        WHERE   real_a.username = a.username 
            AND real_a.setting = b.Possible_Setting)
ORDER BY 1, 2

设置代码:

CREATE TABLE TableA (username varchar(20), setting tinyint)
CREATE TABLE TableB (Possible_Setting tinyint PRIMARY KEY)

INSERT TableA VALUES 
('Mark',          1),
('Mark',          2),
('Martin',        2),
('Jane',           1)

INSERT TableB VALUES 
(1),
(2),
(3)