[英]Laravel 4 - Select rows where count of rows in joined table greater than 0
[英]select rows where count of 2 fields is greater than 1 with where clause
我有一個看起來像這樣的表:
╔════╦═════════╦═════════╦═══════╗
║ id ║ deleted ║ status ║ ref ║
╠════╬═════════╬═════════╬═══════╣
║ 1 ║ 0 ║ pending ║ 10001 ║
║ 2 ║ 0 ║ paid ║ 10001 ║
║ 3 ║ 0 ║ paid ║ 10001 ║
║ 4 ║ 0 ║ paid ║ 10002 ║
║ 5 ║ 1 ║ pending ║ 10002 ║
║ 6 ║ 1 ║ paid ║ 10002 ║
║ 7 ║ 0 ║ pending ║ 10003 ║
║ 8 ║ 0 ║ paid ║ 10003 ║
║ 9 ║ 0 ║ paid ║ 10003 ║
║ 10 ║ 0 ║ paid ║ 10003 ║
║ 11 ║ 0 ║ pending ║ 10004 ║
║ 12 ║ 0 ║ paid ║ 10004 ║
║ 13 ║ 1 ║ pending ║ 10005 ║
║ 14 ║ 1 ║ paid ║ 10005 ║
║ 15 ║ 1 ║ paid ║ 10005 ║
║ 16 ║ 0 ║ paid ║ 10005 ║
║ 17 ║ 0 ║ pending ║ 10006 ║
║ 18 ║ 0 ║ paid ║ 10006 ║
║ 19 ║ 0 ║ paid ║ 10006 ║
╚════╩═════════╩═════════╩═══════╝
我正在嘗試編寫一個MySQL查詢,它將返回已paid
但未deleted
的行。 但只有在paid
計數大於1的情況下,結果應該是:
╔════╦═════════╦════════╦═══════╗
║ id ║ deleted ║ status ║ ref ║
╠════╬═════════╬════════╬═══════╣
║ 2 ║ 0 ║ paid ║ 10001 ║
║ 3 ║ 0 ║ paid ║ 10001 ║
║ 8 ║ 0 ║ paid ║ 10003 ║
║ 9 ║ 0 ║ paid ║ 10003 ║
║ 10 ║ 0 ║ paid ║ 10003 ║
║ 18 ║ 0 ║ paid ║ 10006 ║
║ 19 ║ 0 ║ paid ║ 10006 ║
╚════╩═════════╩════════╩═══════╝
我一直試圖使用以下查詢得到這個,但它沒有做我需要的東西,現在我似乎在繞圈子。 有人可以幫我一把嗎?
SELECT t1.* FROM orders t1 WHERE exists (SELECT * FROM orders t2 where t1.id != t2.id and t1.ref = t2.ref and t1.deleted = 0 and t1.status = 'paid')
非常感謝!
[編輯] arrgh! 對不起,我忘了說我只需要返回超過1個paid
狀態的行...對不起......
請使用以下內容(沒有數據庫實例):
SELECT t.*
FROM orders t
INNER JOIN
(
SELECT ref, deleted, status
FROM orders
WHERE deleted = 0 and status = 'paid'
GROUP BY ref
HAVING count(ref) > 1
) d
ON t.ref = d.ref
AND t.status = d.status
AND t.deleted = d.deleted;
給這個打擊:
select o.*
from orders o
inner join
(
select ref,
sum(case when status = 'paid' then 1 else 0 end) as paid_count,
count(distinct status) as total_distinct_status_count
from orders yt
where deleted = 0
group by ref
) t1 on t1.ref = o.ref
where o.status = 'paid'
and o.deleted = 0
and t1.paid_count > 1
and t1.total_distinct_status_count > 1;
似乎給出了你發布的數據給出的答案。
我認為你正在努力解決這個問題...休息一下再次啟動你的代碼。 無論如何答案已經在第一個回答中給出了...... Chilllllll
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.