我有两张桌子:
Users Messages
--------- ---------
[ FirstName ] [ FirstName ]
[ LastName ] [ LastName ]
[ SSN ] [ SSN ]
[ Message ]
我有以下查询Microsoft SQL:
SELECT
t2.FirstName,
t2.LastName,
t2.SSN
FROM
[Messages] as t1
JOIN
[User] as t2
ON
t1.SSN = t2.SSN
它给我的是两个表中存在的结果。我需要做的只是从Messages表中提取记录,如果他们的SSN在Users表中不存在。我知道有第二步涉及但无法弄清楚。
更新:实际上它仍然不起作用。我在数据库中绝对没有NULL。所有记录都填充了数据。我需要的是来自Messages表的所有记录,这些记录在Users表中不存在。
示例:
Users [ 1 John Smith 111-11-1111 ]
Users [ 2 Jim Tompson 999-99-9999 ]
Messages [ 1 John Smith 111-11-1111 ]
Messages [ 2 Jim Tompson 999-99-9999 ]
Messages [ 3 Angelina Jolie 888-88-8888 ]
[ 3 Angelina Jolie 888-88-8888 ]
答案 0 :(得分:2)
SELECT
t1.FirstName,
t1.LastName,
t1.SSN
FROM
[Messages] as t1
LEFT JOIN
[User] as t2
ON
t1.SSN = t2.SSN
WHERE
T2.ssn is null
答案 1 :(得分:2)
SELECT *
FROM messages m
WHERE NOT EXISTS
(
SELECT NULL
FROM users u
WHERE u.ssn = m.ssn
)
答案 2 :(得分:1)
试试这个:
SELECT
t2.FirstName,
t2.LastName,
t2.SSN
FROM
[Messages] t2
WHERE
t2.SSN
NOT IN
(
SELECT DISTINCT
SSN
FROM
[Users]
)