将来自UNION的MySQL查询转换为更高效的方法

时间:2011-02-09 20:51:10

标签: mysql

我的网站上有自定义消息功能,当我显示用户拥有的消息数时,我使用联合查询,因为有两种类型的消息。

我这样做:

SELECT COUNT(m.messageid) type_a_messagecount
FROM messages m,
messagerecipients r
WHERE m.messageid = r.messageid AND
(
m.type = 0 OR
m.type = 2
) AND
r.read = 0 AND
r.trashed = 0 AND
r.deleted = 0 AND
r.userid = 1 AND
r.authorid <> 1
UNION
SELECT COUNT(m.messageid) type_b_messagecount
FROM messages m,
messagerecipients r
WHERE m.messageid = r.messageid AND
(
m.type = 1
) AND
r.read = 0 AND
r.trashed = 0 AND
r.deleted = 0 AND
r.userid = 1 AND
r.authorid <> 1

这有效,但有些东西告诉我它效率非常低。

有没有办法简化这一点,还是我坚持使用UNION查询?

感谢。

3 个答案:

答案 0 :(得分:1)

怎么样?
SELECT COUNT(m.messageid),m.type
FROM messages m,
  messagerecipients r
WHERE m.messageid = r.messageid AND
  m.type IN (0,1,2) AND
  r.read = 0 AND
  r.trashed = 0 AND
  r.deleted = 0 AND
  r.userid = 1 AND
  r.authorid <> 1
GROUP BY m.type

然后以编程方式添加类型0和2的结果

答案 1 :(得分:1)

带有case语句的子查询将为您提供所需内容:

SELECT 
    count(m.messageid), type_
FROM
    (
        SELECT 
            m.messageid
            CASE 
                WHEN m.type = 0 THEN 'a'
                WHEN m.type = 1 THEN 'b'
                WHEN m.type = 2 THEN 'a'
            END as type_
            FROM 
                messages m,messagerecipients r
            WHERE 
                m.messageid = r.messageid 
                AND r.read = 0
                AND r.trashed = 0
                AND r.deleted = 0
                AND r.userid = 1 AND
                AND r.authorid <> 1
    ) as t
GROUP BY type_

答案 2 :(得分:1)

Select Sum(Case When M.type In(0,2) Then 1 Else 0 End) As type_a_messagecount
    , Sum(Case When M.type = 1 Then 1 Else 0 End) As type_b_messagecount
From messages As M
    Join messagerecipients As R
        On R.messageid = M.messageid
Where R.read = 0 
    And R.trashed = 0 
    And R.deleted = 0 
    And R.userid = 1 
    And R.authorid <> 1