使用group by显示多个表中的相同字段

时间:2014-03-07 07:08:39

标签: mysql sql

Table 1
id_mkt - varchar,
point - varchar

Table 2
id_mkt - varchar,
point - varchar

这是我的代码:

//表1

SELECT * FROM data1 GROUP by id_mkt asc limit 10

//表2

SELECT * FROM data2 GROUP by id_mkt asc limit 10

result table 1: 
id_mkt   | point  
  1      | 100   
  2      | 200 
  4      | 300   

result table 2: 
id_mkt   | point 
  3      | 300   
  2      | 400 
  1      | 100  

我希望得到这样的结果:

id_mkt   | point 
  1      | 200 
  2      | 600
  3      | 300  
  4      | 300 

感谢您的帮助

5 个答案:

答案 0 :(得分:0)

SELECT t.id_mkt, SUM(t.point) AS total FROM
(
  (SELECT * FROM table2)
  UNION
  (SELECT * FROM table1)
) AS t 
GROUP BY id_mkt;

答案 1 :(得分:0)

您可以先将两个表结合起来。

SELECT
  id_mkt, SUM(point) AS point
FROM (
  SELECT * FROM data1
  UNION ALL
  SELECT * FROM data2
) A 
GROUP BY id_mkt

答案 2 :(得分:0)

试试这个:

select id_mkt, sum(t.point) as point
from 
(select * from table1
union 
select * from table2) t
group by id_mkt

sqlfiddle

答案 3 :(得分:0)

尝试下面的一个:

SELECT a.id_mkt, SUM(a.point) AS 'point'
FROM
((SELECT id_mkt,`point` FROM data1)
UNION ALL
(SELECT id_mkt,`point` FROM data2)) a 
GROUP BY a.id_mkt;

答案 4 :(得分:0)

试试这个:

SELECT 
data1.id_mkt, data1.point + data2.point point
FROM
    data1
        JOIN
    data2 ON data1.id_mkt = data2.id_mkt 
UNION SELECT 
    data1.id_mkt, data1.point
FROM
    data1
WHERE
    id_mkt NOT IN (SELECT 
            data1.id_mkt
        FROM
            data1
                INNER JOIN
            data2 ON data1.id_mkt = data2.id_mkt) 
UNION SELECT 
    data2.id_mkt, data2.point
FROM
    data2
WHERE
    id_mkt NOT IN (SELECT 
            data2.id_mkt
        FROM
            data1
                INNER JOIN
            data2 ON data1.id_mkt = data2.id_mkt)
ORDER BY id_mkt;