最近遇见了这样一个问题,有4张表,A(单据)表,B(产品)表,C(产品类型),D(单据产品关联表)。
B表有唯一对应的类型C(B join C on C.ID = B.CID)
A表通过两种方式和B表关联(必定只使用其中一种方式关联)。
一是A中存了一个B.ID作为外键关联B(A join B on B.ID = A.BID),
二是通过关联中间表D,再去关联B(A join D on D.AID = A.ID join B on B.ID = D.BID)。
现在需要查询符合一定条件全部N类型产品(C.NAME = N)的单据信息。结果根据单据A.startLifecycle(生成时间)排序;
看到需求第一时间想到的是UNION连接查询结果。
于是:
SELECT a.id, a.startLifecycle FROM A a
JOIN D d ON d.aid = a.id
JOIN B b ON b.id = d.bid
JOIN C c ON c.id = b.cid
WHERE c.name = 'N' AND ...
ORDER BY a.startLifecycle, a.id
UNION
SELECT a.id, a.startLifecycle FROM A a
JOIN B b ON b.id = a.bid
JOIN C c ON c.id = b.cid
WHERE c.name = 'N' AND ...
ORDER BY a.startLifecycle, a.id
好吧!出问题了,上网查了下,是UNION和ORDER BY一起使用引起的。
然后尝试了下其他方法(略),最后解决方案如下。
--A的过滤条件很多,先过滤A
WITH
t1 AS(SELECT a.id, a.startLifecycle FROM A a WHERE ...),
t2 AS(SELECT t1.id, t1.startLifecycle FROM t1JOIN D d ON d.aid = t1.id JOIN B b ON b.id = d.bidJOIN C c ON c.id = b.cidWHERE c.name = 'N'ORDER BY t1.startLifecycle, t1.id
),
t3 AS(SELECT t1.id, t1.startLifecycle FROM t1JOIN B b ON b.id = t1.bidJOIN C c ON c.id = b.cidWHERE c.name = 'N'ORDER BY t1.startLifecycle, t1.id
)
SELECT id, startLifecycle FROM t2
UNION
SELECT id, startLifecycle FROM t3;