Sql合并查询

时间:2014-10-15 12:43:23

标签: mysql sql merge

我有这些疑问。

Yii::app()->db->createCommand("SELECT SUM(comment) FROM `tbl_1` t1 LEFT JOIN `tbl_2` t2 on  t1.id_id = t2.id WHERE create_time >= UNIX_TIMESTAMP(NOW() - INTERVAL 1 DAY)")->queryScalar();
Yii::app()->db->createCommand("SELECT SUM(comment) FROM `tbl_1` t1 LEFT JOIN `tbl_2` t2 on   t1.id_id = t2.id WHERE create_time >= UNIX_TIMESTAMP(NOW() - INTERVAL 1 WEEK)")->queryScalar();
Yii::app()->db->createCommand("SELECT SUM(comment) FROM `tbl_1` t1 LEFT JOIN `tbl_2` t2 on t1.id_id = t2.id WHERE create_time >= UNIX_TIMESTAMP(NOW() - INTERVAL 1 MONTH)")->queryScalar();

如何在一个查询中写这个?

2 个答案:

答案 0 :(得分:0)

由于@geoandri说条件重叠所以只有一个查询的唯一方法就是使用子查询联合,但你不能获得任何表现。

答案 1 :(得分:0)

我认为你的问题确实是"我如何编写一个返回这三列的行的查询?"

我无法在MySql中测试这个。如果我必须在SQL中执行此操作,我将使用如下命令:

SELECT
    day_total = SUM(
        CASE
        WHEN create_time >= UNIX_TIMESTAMP(NOW() - INTERVAL 1 DAY)
        THEN comment
        ELSE 0
        END
    ),
    week_total = SUM(
        CASE
        WHEN create_time >= UNIX_TIMESTAMP(NOW() - INTERVAL 1 WEEK)
        THEN comment
        ELSE 0
        END
    ),
    month_total = SUM(comment)

FROM `tbl_1` t1
LEFT JOIN `tbl_2` t2 on  t1.id_id = t2.id
WHERE create_time >= UNIX_TIMESTAMP(NOW() - INTERVAL 1 MONTH)

注意:默认情况下,WHERE子句选择的任何内容都属于一个月类别,这就是我从CASE WHEN ... END的{​​{1}}中删除SUM()的原因列。