假设您有以下两个SQL Server表:
T1:
|----------------------------------------------|
|name | day_planed | day_canceled | discription|
|----------------------------------------------|
|alpha| 2015-11-02 | 2015-11-01 | some |
|alpha| 2015-11-02 | 2015-10-30 | text |
|beta | 2015-11-02 | 2015-11-01 | here |
|----------------------------------------------|
T2:
|----------------------------------------------|
|name | day_planed | day_canceled | discription|
|----------------------------------------------|
|alpha| 2015-11-02 | 2015-10-30 | text |
|----------------------------------------------|
在t1的查询中,我现在想要除t2之外的每个条目。我已经尝试了类似于
的东西SELECT *
FROM t1 AS A
LEFT JOIN t2 as B ON (A.name = B.name
AND A.day_planed = B.day_planed
AND A.day_canceled != B.day_canceled)
不幸的是,我不明白为什么它不会在t1的查询中排除t2中的行。
第二个问题是,如果有一个简单的方法,只需返回具有最大描述的行,就可以在没有t2的情况下查询t1。我尝试在SQL Server中查看它,但只能找到第一个标识符,它不适用于此"精彩"执行sql ...
答案 0 :(得分:2)
在这个“精彩”的实施中,有几种方法可以做到。
SELECT *
FROM t1
WHERE NOT EXISTS
( SELECT *
FROM t2
WHERE t2.name = t1.name
AND t2.day_planed = t1.day_planed
AND t2.day_canceled = t1.day_canceled
)
是一个。另一个是:
LEFT JOIN
或者您可以使用WHERE t2.name IS NULL
并在ON子句后检查与SELECT t1.*
FROM t1
LEFT JOIN t2
ON t2.name = t1.name
AND t2.day_planed = t1.day_planed
AND t2.day_canceled = t1.day_canceled
WHERE t2.name IS NULL;
不匹配的行。就像你拥有的那样但是=而不是!=
discription
如果您想检查每一列(包括{{1}}),请使用EXCEPT。
答案 1 :(得分:2)
你只是缺少一个where子句和一个关于描述的条件。您还需要更改!= to =。
SELECT *
FROM t1 AS A
LEFT JOIN t2 as B ON (A.name = B.name
AND A.day_planed = B.day_planed
AND A.day_canceled = B.day_canceled
AND A.discription = B.discription)
WHERE B.Name IS NULL