我有一些表,这些表的列如下所示:
Customer: cid, blah
Product: pid, blah
Order: cid, pid
我想要具有以下列的结果表:
cid,pid,(当按顺序排列该行的(cid,pid)时为“ true”,否则为“ false”)
例如:
客户
1 blah
2 blah
3 blah
产品
1 blah
2 blah
3 blah
4 blah
订单
1 2
1 3
2 1
2 4
3 3
我想查找具有以下结果的sql查询:
1 1 false
1 2 true
1 3 true
1 4 false
2 1 true
2 2 false
2 3 false
2 4 true
3 1 false
3 2 false
3 3 true
3 4 false
我正在尝试找出该查询,但仅限于我所知。有人知道如何编写该查询吗?
// 抱歉,忘记提及我也要从结果中获得客户和产品的帮助
cid, blah, pid, blah, true/false
答案 0 :(得分:1)
您可以cross
和left
加入,并且case..when
条件语句为:
select c.cid, p.pid,
( case when o.cid*o.pid > 0 then 'true' else 'false' end )
as flag
from product p
cross join customer c
left join order_ o on o.cid = c.cid and o.pid = p.pid
order by c.cid, p.pid;
P.S。 order 是关键字,所以我用 order _
答案 1 :(得分:0)
SELECT C.CID,P.PID,
CASE WHEN C.CID,P.PID IN
(SELECT CID,PID from
ORDER)
THEN "TRUE" END CASE
CASE WHEN C.CID,P.PID NOT IN
(SELECT CID,PID from
ORDER)
THEN "FALSE" END CASE
FROM CUSTOMER C,PRODUCT P ;
您需要为此提供案例说明。
答案 2 :(得分:0)
这是最简单的方法:
(
SELECT O.cid, O.pid, 'true'
FROM order O
Where (O.cid, O.pid) in
(SELECT C.cid, p.pid,
FROM customer C CROSS JOIN product P)
)
UNION
(
SELECT O.cid, O.pid, 'false'
FROM order O
Where (O.cid, O.pid) not in
(SELECT C.cid, p.pid,
FROM customer C CROSS JOIN product P)
)