我有一个查询如下
SELECT
sum(price),
count(id),
sum case(when spec='bath' then price else 0 END) as bath_money
FROM
table1
LEFT JOIN table2 ON table1.id = table2.fkt1
LEFT JOIN table3 ON table2.id = table3.fkt2
WHERE 1
group by sale;
现在我的问题是表3在表2中每行有2行。表2是我实际用于累加销售额和总和价格的那一行但由于我需要为表3保留连接,所以一切都添加了两次。 是否有办法将表2的价格加起来而忽略了加入表3所产生的所有双线?否则我只是写另一个查询,但我想知道我是否可以做一个忽略特定连接的总和?
答案 0 :(得分:0)
您可以尝试类似
的内容SELECT
sum(t1.price),
count(t1.id),
sum (case when t2.spec='bath' then t2.price else 0 END) as bath_money
FROM
table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.fkt1
LEFT JOIN table3 t3 ON t2.id = t3.fkt2
group by t1.sale
答案 1 :(得分:0)
这是否有效:
SELECT
sum(price),
count(id),
sum(case when spec='bath' then price else 0 END) as bath_money
FROM table1 t1
LEFT JOIN table2 ON table1.id = table2.fkt1
LEFT JOIN (select * from table3 GROUP BY fkt2) table3a ON table2.id = table3a.fkt2
group by sale;