子查询返回更多行

时间:2019-05-10 11:53:12

标签: mysql

我在使用此mysql代码时遇到问题

mysql模式

att (`e_id`, `state`, `date`, `time`)

(1, '0', '2019-05-09', '9:39:50'),
(1, '1', '2019-05-09', '15:39:5'),
(2, '0', '2019-05-09', '8:39:50'),
(2, '1', '2019-05-09', '16:39:5');

我的代码返回此错误(子查询返回1行以上)

SELECT att.e_id, att.date, 
(SELECT time FROM att WHERE e_id = att.e_id AND state = '0' ) as 'enter_time', 
(SELECT time FROM att WHERE e_id = att.e_id AND state = '1' ) as 'end_time' 
from att GROUP BY e_id, date

2 个答案:

答案 0 :(得分:2)

您的问题是,在子查询中,MySQL不知道您在e_id子句中表示的WHERE的值是什么,因此它从att中选择一个,然后将其匹配为att中的所有行,其值都为state。您需要通过使用表别名限定它来告诉MySQL使用表副本中的版本:

SELECT att.e_id, att.date, 
(SELECT time FROM att a2 WHERE a2.e_id = att.e_id AND state = '0' ) as 'enter_time', 
(SELECT time FROM att a2 WHERE a2.e_id = att.e_id AND state = '1' ) as 'end_time' 
from att GROUP BY e_id, date

输出:

e_id    date        enter_time  end_time
1       2019-05-09  09:39:50    15:39:05
2       2019-05-09  08:39:50    16:39:05

Demo on dbfiddle

您可以通过条件聚合更有效地做到这一点:

SELECT att.e_id, att.date, 
MAX(CASE WHEN state = 0 THEN time END) as 'enter_time', 
MAX(CASE WHEN state = 1 THEN time END) as 'end_time' 
from att 
GROUP BY e_id, date;

Demo on dbfiddle

答案 1 :(得分:1)

无需子查询

请尝试以下方法:

SELECT a.e_id, a.date, enter.time  as 'enter_time',endd.time as 'end_time'
  from att a,
       att enter,
       att endd
 where enter.state='0' 
   and endd.state='0' 
   and enter.e_id=a.e_id 
   and endd.e_id=a.e_id
   and a.state='0'  
 order by a.e_id, a.date

如果要使用查询,请在主查询中添加state ='0'并修复别名

SELECT b.e_id, b.date, 
(SELECT time FROM att a WHERE a.e_id = b.e_id AND a.state = '0' ) as 'enter_time', 
(SELECT time FROM att a WHERE a.e_id = b.e_id AND a.state = '1' ) as 'end_time' 
from att b where b.state='0' 

SQLFiddle http://sqlfiddle.com/#!9/e7dcafb/14上的演示