鑒于表
| eventId | orderId |
| 18 | 20 |
| 19 | 20 |
| 20 | 21 |
我只想選擇在給定特定 eventId(比如說 18)的情況下,它的 orderId 沒有與之關聯的其他 eventId 的行。
因此,在上述情況下,對于 eventId 18 或 19,它不會回傳任何內容,但對于 eventtId 20,它將回傳整行。
uj5u.com熱心網友回復:
SELECT *
FROM tbl t1
WHERE NOT EXISTS (SELECT *
FROM tbl t2
WHERE t1.orderId = t2.orderId
AND t1.eventId != t2.eventId)
SQL小提琴: http ://sqlfiddle.com/#!9/bf1422a/1
uj5u.com熱心網友回復:
使用聚合:
SELECT MAX(eventId) eventId, orderId
FROM tablename
GROUP BY orderId
HAVING COUNT(*) = 1; -- or HAVING COUNT(DISTINCT eventId) = 1
該條件HAVING COUNT(*) = 1將僅回傳與僅orderId相關的行eventId并且這將等于MAX(eventId)(因為它是唯一的)。
僅當和HAVING COUNT(DISTINCT eventId) = 1的組合不唯一時才使用條件。eventIdorderId
uj5u.com熱心網友回復:
你可以使用聚合
SELECT orderId
FROM tbl t1
group by orderId
having count(distinct eventId)=1
uj5u.com熱心網友回復:
使用GROUP BY,HAVING確保 eventId 不共享其 orderId:
select eventId, orderId
from
(
select min(eventId) eventId, orderId
from tbl
group by orderId
having count(*) = 1
) dt
where eventId = 18;
LEFT JOIN版本:
select t1.eventId, t1.orderId
from tbl t1
left join tbl t2 on t1.orderId = t2.orderId and t1.eventId <> t2.eventId
where t2.orderId is null
and t1.eventId = 18
uj5u.com熱心網友回復:
如果表被稱為測驗這個查詢應該作業
select t.order_id, t.event_id from test t join
( select event_id, count(*) tm from test GROUP by event_id) a
on t.event_id = a.event_id
where a.tm = 1
and t.order_id = 20
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/430041.html
上一篇:GPG密鑰只能作業幾分鐘
下一篇:將一行從對偶拆分為幾個不同的列
