如何将两个不同的查询结果合并为一列

时间:2014-02-13 22:56:21

标签: mysql sql

我正在尝试通过字段ANCHOR合并两个查询的结果,该字段在两个查询中返回相等的值

 SELECT
    anchor_date AS anchor, <======================= query one, field "anchor"
    SUM( GETVAL(24, entry_id) ) AS valueQ1 <======= query one, field "valueQ1"
 FROM users
 WHERE blog_id = 173
 GROUP BY DATE(anchor)

 UNION

 SELECT
    anchor AS anchor, <============================ query two, field "anchor"
    SUM(value) AS valueQ2 <======================== query two, field "valueQ2"
 FROM infodata
 WHERE infoid IN(330, 1492, 1066)
 AND entity = 173

我需要这样的结果:

anchor      valueQ1      valueQ2
------      -------      -------
abcdef      123          456
abcdef      123          456
abcdef      123          456

我正在尝试使用UNION而没有成功。也许是INTERSECT或JOIN?

1 个答案:

答案 0 :(得分:2)

SELECT anchor, MAX(valueQ1) AS valueQ1, MAX(valueQ2) AS valueQ2
FROM (
    SELECT
        anchor_date AS anchor,
        SUM( GETVAL(24, entry_id) ) AS valueQ1,
        NULL AS valueQ2
     FROM users
     WHERE blog_id = 173
     GROUP BY DATE(anchor)

     UNION

     SELECT
        anchor AS anchor,
        NULL AS valueQ1,
        SUM(value) AS valueQ2
     FROM infodata
     WHERE infoid IN(330, 1492, 1066)
     AND entity = 173) AS u
GROUP BY anchor