2012-10-17 52 views
0

我需要完善這個SQL SELECT:MySQL的 - 過濾器聲明

SELECT ch_num, payment_type, Total FROM transactions WHERE (ch_num) 
IN (
SELECT ch_num FROM transactions GROUP BY ch_num HAVING count('ch_num') > 1 
) 
ORDER BY `ch_num` 

結果我得到的是:

ch_num payment_type Total 
20001 visa  36.60 
20001 visa  36.60 
20001 mc   30.60 
50019 cash  9.00 
50019 mc   18.95 
50023 cash  2.70 
50023 visa  7.00 

但我需要的結果行只有在有 '現金' payment_type如此「應該省略ch_no'20001。 正確的結果將是,那麼:

ch_num payment_type Total 
50019 cash  9.00 
50019 mc   18.95 
50023 cash  2.70 
50023 visa  7.00 

回答

0

這裏有一個完整的,經過驗證的代碼示例,並在最後的測試結果。我使用了Oracle,但SQL SELECT的語法應該相同。

create table transactions (ch_num int, payment_type varchar2(100), total float); 

insert into transactions values(20001,'visa',36.60); 
insert into transactions values(20001,'mc',30.60); 
insert into transactions values(50019,'cash',9.00); 
insert into transactions values(50019,'mc',18.95); 
insert into transactions values(50023,'cash',2.70); 
insert into transactions values(50023,'visa',7.00); 

SELECT ch_num, payment_type, Total FROM transactions a WHERE (ch_num) 
IN (
SELECT ch_num FROM transactions GROUP BY ch_num HAVING count(ch_num) > 1 
) 
AND EXISTS 
(SELECT ch_num FROM transactions b where payment_type = 'cash' and a.ch_num = b.ch_num) 
ORDER BY ch_num 

結果:

CH_NUM PAYMENT_TYPE TOTAL 
1 50019 cash 9 
2 50019 mc 18.95 
3 50023 cash 2.7 
4 50023 visa 7 
+0

由於某種原因,這個選擇是快一點(只有在phpMyAdmin測量)..任何想法,爲什麼? – phpJs

+0

@phpJs - 您可以查看優化程序計劃並在2個查詢之間進行比較,以查看有什麼不同。 – dcp

1
SELECT ch_num, payment_type, Total 
FROM transactions 
WHERE ch_num IN 
(
     SELECT ch_num 
     FROM transactions 
     GROUP BY ch_no 
     HAVING count('ch_num') > 1 
     and sum(payment_type='cash') >= 1 
) 
ORDER BY `ch_num` 
+0

這個選擇效果很好。 – phpJs