将两个查询合并为一个

时间:2013-07-28 12:19:50

标签: php mysql

我有两种类型的消息,一种是私人消息,另一种是信用消息正在插入两个不同的表。现在我正在尝试获取数据。

SELECT * ,(SELECT COUNT(*) 
           FROM votes 
           WHERE message_id = m.message_id
             AND vote_type = 'like') AS likes,
          (SELECT COUNT(*) 
           FROM votes
           WHERE message_id = m.message_id 
           AND vote_type = 'dislike') AS dislikes 
FROM messages m
WHERE 1 #and hidden is null
  and recipient_id = 1
ORDER BY datetime DESC

SELECT * ,(SELECT COUNT(*) 
           FROM votes 
           WHERE message_id = m.message_id
             AND vote_type = 'like') AS likes,
          (SELECT COUNT(*)
           FROM votes
           WHERE message_id = m.message_id  
             AND vote_type = 'dislike') AS dislikes 
FROM private_messages m 
WHERE 1 #and hidden is null 
  and recipient_id = 1 
ORDER BY datetime DESC

现在想要将它们合并到一个查询中,一个额外的参数将显示其私人消息或信用消息。

3 个答案:

答案 0 :(得分:2)

如果现有查询执行您想要/需要的操作,UNION将使它们组合起来非常简单,例如;

SELECT * FROM (
    SELECT is_private 0, <field1>,<field2>,<field3>, ... ,(SELECT COUNT(*) 
               FROM votes 
               WHERE message_id = m.message_id
                 AND vote_type = 'like') AS likes,
              (SELECT COUNT(*) 
               FROM votes
               WHERE message_id = m.message_id 
               AND vote_type = 'dislike') AS dislikes 
    FROM messages m
    WHERE 1 #and hidden is null
      and recipient_id = 1
    UNION ALL
    SELECT 1, <field1>, <field2>, <field3>, ... ,(SELECT COUNT(*) 
               FROM votes 
               WHERE message_id = m.message_id
                 AND vote_type = 'like') AS likes,
              (SELECT COUNT(*)
               FROM votes
               WHERE message_id = m.message_id  
                 AND vote_type = 'dislike') AS dislikes 
    FROM private_messages m 
    WHERE 1 #and hidden is null 
      and recipient_id = 1 
)
ORDER BY datetime DESC

请注意,您需要从两个查询中选择相同的数字/顺序列,才能使联合工作。 SELECT *使得很难验证是否是这种情况。如果

答案 1 :(得分:0)

您可以使用UNION组合mysql查询:

SELECT id FROM table_user 联盟 SELECT COUNT(投票)FROM table_vote

您可以使用UNION的多个UNION查询。

喜欢,

查询1

UNION

查询2

UNION

..... ..... .....

查询n

答案 2 :(得分:0)

我认为以下是一种表达逻辑的简单方法:

select m.*, v.likes, v.dislikes
from (select v.message_id, sum(vote_type = 'like') AS likes, sum(vote_type = 'dislike') AS dislikes
      from votes v
      group by v.message_id
     ) v join
     (select m.*, 'Message' as which
      from messages
      union all
      select pm.*, 'PrivateMessage' as which
      from private_messages pm
     ) m
     on v.message_id = m.message_id;