Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
mysql-filter-IN语句_Mysql_Sql - Fatal编程技术网

mysql-filter-IN语句

mysql-filter-IN语句,mysql,sql,Mysql,Sql,我需要优化此sql选择: 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 3

我需要优化此sql选择:

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
但我只需要有“现金”支付类型的结果行,所以“Chu no”20001应该省略。 正确的结果是:

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

下面是一个完整的、经过验证的代码示例,最后是测试结果。我使用了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

由于某些原因,此选择速度稍快(仅以phpMyAdmin为单位)。。知道为什么吗?@phpJs-您可以查看优化器计划并在两个查询之间进行比较,看看有什么不同。
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`