加入两个查询,并从两个表中按两个字段分组

时间:2015-09-23 20:16:42

标签: mysql

我有这些疑问

SELECT CA_id, item_id, item_Cant, item_desc FROM items WHERE CA_id = 135

enter image description here

SELECT CA_id, prov_name, unitval, totval FROM provprices WHERE CA_id = 135 AND prov_name = 'SITECH'

enter image description here

我希望加入这两个结果,就像:

item_id - item_Cant - item_desc - unitval - totval

我尝试了不同的形式,但我能得到的最大值是: (如果你注意到第二个表的结果是公开的,应该像第二个图像一样)

SELECT items.item_id,items.item_Cant,items.item_desc,provprices.unitval,provprices.totval 
FROM items,provprices 
WHERE items.CA_id = provprices.CA_id
AND provprices.prov_name = 'SITECH' 
AND items.CA_id = '135' 
GROUP BY items.item_id

enter image description here

如果我更改为GROUP BY provprices.unitval,现在重复的结果是第一个

enter image description here

我希望你能帮助我。感谢

1 个答案:

答案 0 :(得分:0)

我不太了解,但试试这个,

您想如何计算单位数和总数

       select item_id, item_Cant, item_desc, AVG(unitval), sum(totval)
        from (
             SELECT CA_id, item_id, item_Cant, item_desc
             FROM items
             WHERE CA_id = 135
        ) A
        inner join (
             SELECT CA_id, prov_name, unitval, totval
             FROM provprices
             WHERE CA_id = 135 AND prov_name = 'SITECH'
        ) B ON A.CA_id=B.CA_id
GROUP BY item_id, item_Cant, item_desc