Mysql连接两个选择

时间:2014-08-07 18:52:50

标签: mysql sql

我有一个表(列表),其中包含名称列表和第二个表(rec),其中包含第一个表中id引用的价格记录。

第二个表(rec)标题如下:

price|fk_id|what

我尝试计算第一张表中所有名称的价格总和,但除以 列。什么可以包含:维修和购买 例如:

NAME |REPAIR|BUY
----------------
Name1|   120|340
Name2|    20|40

我知道创建sql到REPAIR:

SELECT z.name, COALESCE(SUM(zb.price), 0) AS REPAIR FROM list z
LEFT JOIN rec zb ON zb.fk_id = z.id AND zb.what = "repair" 
GROUP BY z.id
ORDER BY z.id

如何连接第二列BUY? 我试着:

SELECT z.name, COALESCE(SUM(zb.price), 0) AS REPAIR, col2.BUY FROM list z
JOIN (
...The same select with zb.what = buy..
) as col2
LEFT JOIN rec zb ON zb.fk_id = z.id AND zb.what = "repair" 
GROUP BY z.id
ORDER BY z.id

但它无法正常工作。

1 个答案:

答案 0 :(得分:0)

您无法加入仅在子查询中的表和列。您必须更改子查询,以便它还返回z.id,然后加入ON zb.fk_id = col2.id。但是你不需要子查询,你可以在一个查询中完成所有操作:

SELECT z.name, 
        COALESCE(SUM(IF(zb.what = "repair", zb.price, 0)), 0) AS repair,
        COALESCE(SUM(IF(zb.what = "buy", zb.price, 0)), 0) AS buy
FROM list AS z
LEFT JOIN rec AS zb ON zb.fk_id = z.id
GROUP BY z.id
ORDER BY z.id