将Join / Subselect查询与SUM MYSQL查询组合在一起

时间:2012-12-16 14:06:15

标签: mysql sql

第一个MYSQL查询

-- selects the latest records by unique member_id
SELECT * FROM table t
JOIN (SELECT MAX( id ) AS id
FROM table
GROUP BY member_id) t2 ON t2.id = t.id
WHERE `t`.`timestamp` >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
ORDER BY t.id DESC
LIMIT 10 

第二

-- sums the item_qt column by unique member_id
SELECT SUM(item_qt) AS sum_item_qt FROM table t
WHERE `t`.`timestamp` >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
GROUP BY member_id
ORDER BY t.id DESC
LIMIT 10 

有没有办法合并这两个查询,以便连接sum_item_qt 在member_id上?

2 个答案:

答案 0 :(得分:3)

我认为此查询应该为您提供所需的答案:

SELECT *
FROM table1 t
INNER JOIN
(SELECT MAX(id) AS id, SUM(item_qt) AS sum_item_qt
 FROM table1
 WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
 GROUP BY member_id) AS t2
ON t2.id = t.id
ORDER BY t.id DESC
LIMIT 10

答案 1 :(得分:1)

SELECT  a.*, c.*
FROM    tableName a
        INNER JOIN
        (
            SELECT member_ID, max(ID) maxID
            FROM tableName
            GROUP BY member_ID
        ) b ON  a.member_ID = b.member_ID AND
                a.ID = b.ID
        INNER JOIN
        (
            SELECT  member_ID, SUM(item_qt) sum_item_qt 
            FROM    tableName
            WHERE   timestamp >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
            GROUP BY member_id
        ) c ON  a.member_ID = c.member_ID
-- WHERE
-- ORDER BY
-- LIMIT