如何计算具有相似条件的2个表的mysql结果?

时间:2016-05-27 06:16:20

标签: php mysql

我想在goals的{​​{1}}列中插入总共2个表的数量。

我可以使用1个表,但是我无法将第二个表组合在一起。我错过了什么?

pivot_data

然后

INSERT INTO pivot_data (date, goals)
SELECT CURDATE( ) AS today, COUNT( * ) AS goals

但我也想结合

FROM alerts_data
WHERE DATE( alerts_data_timestamp ) = CURDATE( ) AND alerts_data_status ='goal'

然后

FROM alerts_push_data
WHERE DATE( push_data_timestamp ) = CURDATE( ) AND push_data_status ='goal'

1 个答案:

答案 0 :(得分:1)

尝试使用UNION ALL

INSERT INTO pivot_data (date, goals)
SELECT today, goals
FROM (    
  SELECT CURDATE( ) AS today, SUM( goals ) AS goals
  FROM (
    SELECT COUNT(*) AS goals
    FROM alerts_data
    WHERE DATE( alerts_data_timestamp ) = CURDATE( ) 
          AND alerts_data_status ='goal'

    UNION ALL

    SELECT COUNT(*) AS goals
    FROM alerts_push_data
    WHERE DATE( push_data_timestamp ) = CURDATE( ) 
          AND push_data_status ='goal') AS s ) AS t
ON DUPLICATE KEY UPDATE pivot_data.goals = t.goals