收到错误:
1064 - 您的SQL语法出错;
check the manual that corresponds to your MySQL server version for the right syntax to use near 't1.pard_suma LIMIT 0, 25' at line 5
NO DISTINCT error:
#1054 - Unknown column 't1.pard_suma' in 'having clause'
SELECT t1.invoice_nr
FROM irasai t1
LEFT JOIN apmokejimai t2 ON t1.invoice_nr = t2.invoice_nr
GROUP BY t1.id
HAVING SUM(DISTINCT t2.suma) <> t1.pard_suma
但列存在!
如何解决这个问题?
这就像我需要的那样,但我希望得到所有的invoice_nr,其中pard_suma高于所有apmokejimai.suma(将它们全部用相同的invoice_nr汇总)以及invoice_nr不存在于apkomejimai表中
感谢。
答案 0 :(得分:2)
HAVING
子句在<>
比较运算符的右侧寻找静态值。所以你必须做这样的事情:
SELECT t1.*
FROM irasai t1
LEFT JOIN apmokejimai t2 ON t1.invoice_nr = t2.invoice_nr
GROUP BY t1.id
HAVING SUM(DISTINCT t2.suma) <> (
SELECT MAX(pard_suma)
FROM irasai
WHERE invoice_nr = t1.invoice_nr
GROUP BY invoice_nr
)
示例:http://sqlfiddle.com/#!9/90760/6
create table irasai (
id int,
invoice_nr int,
pard_suma int
);
create table apmokejimai (
invoice_nr int,
suma int
);
insert into irasai values (1, 1, 100);
insert into apmokejimai values (1, 20), (1, 40), (1, 40);
insert into irasai values (1, 1, 200);
insert into apmokejimai values (1, 40), (1, 80), (1, 81);
请注意,我故意在apmokejimai中输入的数据总数不超过200。
在<>
的SQL右侧,我创建了一个子查询,用于计算HAVING
可以与之比较的数字。我猜这有点类似于你想要做的事情。
**在评论中回答OP的问题*
create table irasai (
id int,
invoice_nr int,
pard_suma int
);
create table apmokejimai (
invoice_nr int,
suma int
);
insert into irasai values (1, 1, 100);
insert into apmokejimai values (1, 20), (1, 40), (1, 40);
insert into irasai values (2, 2, 200);
insert into apmokejimai values (2, 40), (2, 80), (2, 81);
insert into irasai values (3, 3, 300);
select
t1.invoice_nr,
max(t1.pard_suma) as pardtotal,
sum(t2.suma) as sumatotal
from irasai t1
left join apmokejimai t2 on t1.invoice_nr = t2.invoice_nr
group by invoice_nr
having pardtotal <> sumatotal or sumatotal is null