我想做出很好的SQL查询,但需要一些帮助......
表A
1 "aaa" "STATUS_OK"
2 "bbb" "STATUS_OK"
3 "ccc" "STATUS_OK"
4 "ddd" "STATUS_NOT_OK"
表B
1 "Addtional Data1" 1/9/2015 2 (foregin Key = TableA.ID)
2 "Addtional Data2" 2/9/2015 2 (foregin Key = TableA.ID)
3 "Addtional Data3" 3/9/2015 2 (foregin Key = TableA.ID)
4 "Addtional Data4" 4/9/2015 2 (foregin Key = TableA.ID)
因此,表A的2“bbb”实体在表B中有4个附加数据
这里我想从表A中提取行
"STATUS_OK"
我想到了这一天。我熟悉基本的SQL语法,但这给我带来了很多困难。
任何人都可以帮我做这个查询吗?
我可以通过在表A中添加“更新时间”来解决问题,但这个解决方案并不是那么可取......
如果我在简单的SQL中出现这种情况,
CREATE TABLE table_A(
ID int NOT NULL,
NAME VARCHAR(20),
STATUS VARCHAR(20),
PRIMARY KEY(ID)
);
CREATE TABLE table_B(
ID int NOT NULL,
DATA VARCHAR(20),
CREATEDATE DATE,
A_ID int,
PRIMARY KEY(ID),
FOREIGN KEY (A_ID) REFERENCES table_A(ID)
);
答案 0 :(得分:0)
一个选项是使用NOT EXISTS
执行此操作:
SELECT ID,NAME,[STATUS]
FROM table_A a
WHERE a.[STATUS] = 'STATUS_OK'
AND NOT EXISTS
(SELECT TOP 1 1
FROM table_B b
WHERE b.A_ID = a.ID
AND DATEDIFF(WEEK,b.CREATEDATE,GETDATE())<=2)
编辑:这是使用LEFT JOIN
的另一个版本:
SELECT a.ID, a.NAME, a.[STATUS]
FROM table_A a
LEFT JOIN table_B b ON a.ID = b.A_ID
AND DATEDIFF(WEEK,b.CREATEDATE,GETDATE())<=2
WHERE a.[STATUS] = 'STATUS_OK'
AND b.A_ID IS NULL
编辑2:使用子查询也可以。在小桌子上,这三个查询没有区别。如果您针对数百万条记录运行它,则必须检查哪种记录最适合您:
SELECT ID,NAME,[STATUS]
FROM table_A a
WHERE a.[STATUS] = 'STATUS_OK'
AND a.ID NOT IN
(SELECT b.A_ID
FROM table_B b
WHERE DATEDIFF(WEEK,b.CREATEDATE,GETDATE())<=2)