我正在尝试在mysql中编写以下查询: -
SELECT *
FROM eon.merged_monthly_energy_data
where consumption>0
and ((SELECT TIMESTAMPDIFF(YEAR, mmed.start_date, CURDATE()) AS difference
FROM merged_monthly_energy_data mmed) <1) ;
但是,我收到以下错误: -
错误代码:1242。子查询返回的行数超过1行
我不确定为什么返回多个结果的子查询会在这里产生问题: -
答案 0 :(得分:1)
您可以使用:
SELECT *
FROM eon.merged_monthly_energy_data
WHERE consumption>0
AND TIMESTAMPDIFF(YEAR, start_date, CURDATE()) < 1
您的原始查询不是逐行检查,而是整个表检查。您可以使用相关子查询来缓解它,但不需要这样:
SELECT *
FROM eon.merged_monthly_energy_data m
WHERE consumption>0
AND ((SELECT TIMESTAMPDIFF(YEAR, mmed.start_date, CURDATE()) AS difference
FROM merged_monthly_energy_data mmed
WHERE mmed.id = m.id) <1) ;
答案 1 :(得分:-1)
要查看错误代码1242的原因,只需将子查询替换为具有多个值的结果
SELECT *
FROM eon.merged_monthly_energy_data
where consumption>0
and ('more than one value' <1);
<
运算符的操作数不兼容,子查询必须返回一个结果。