在单个sql查询中选择多个表

时间:2011-02-21 16:19:32

标签: sql mysql join sql-order-by

关于这一点的其他线索似乎没有帮助我。我想从一个表中选择所有信息,但是按照另一个表中的值对它们进行排序。

SELECT消息,
         date
         IP,
         名,
         网站,
         ID
  来自guestbook_message
  WHERE删除= 0
     和日期> DATE_SUB(NOW(),INTERVAL 1天)
  ORDER BY date DESC“;

除了我需要ORDER BY 'votes' DESC;之外的另一个名为m_votes的表。

有可能这样做吗?我在另一个网站上看到这个查询是不可能的。

$查询=“选择      g.message,      g.date,      g.ip,      g.name,      g.website,      g.id 来自guestbook_message AS g 加入m_votes AS v ON g.id = v.vid 在哪里g.deleted = 0 AND v.messageid = $ mid AND g.date> DATE_SUB(NOW(),INTERVAL 1天) ORDER BY SUM(v.votes)DESC;“

^^这不起作用

4 个答案:

答案 0 :(得分:5)

您需要加入:

SELECT
     g.message,
     g.date,
     g.ip,
     g.name,
     g.website,
     g.id 
FROM guestbook_message AS g
LEFT JOIN m_votes AS v
ON g.id = v.message_id
WHERE g.deleted = 0 
AND g.date > NOW() - INTERVAL 1 DAY
GROUP BY g.id
ORDER BY COUNT(v.message_id) DESC

答案 1 :(得分:1)

我是一个初学者,对我而言,这是一个非常难的查询,因为它需要在m_votes中找到'投票'的SUM并按此顺序排序。以及从其他查询中获取信息。 这是获取有关消息的信息的查询:

 "SELECT message,  
         `date`,  
         ip,  
         name,  
         website,  
         id   
  FROM `guestbook_message`   
  WHERE deleted = 0   
     AND date > DATE_SUB(NOW(), INTERVAL 1 DAY)   
  ORDER BY `date` DESC";  

这是获取有关投票信息的查询:

"SELECT SUM(votes) as votes FROM m_votes WHERE messageid = $mid"

但是我不知道我会把它们放到一个查询中,它会从第一个查询中收集所有信息,然后通过投票对它们进行排序。

答案 2 :(得分:1)

您必须加入数据,也就是说,您需要为每个留言板留言投票。

为简单起见,我们假设您有以下表格:

Message
----
id INT
messsageText VARCHAR(5000)

MessageVotes
------------
messageId INT (references the `id` column in table Message)
voteValue INT (suppose it can be +1 or -1, whatever)
votingIp  VARCHAR(100)

然后你可以做类似

的事情
SELECT
  m.id,
  m.messageText,
  SUM(mv.voteValue) AS votes
FROM
  Message AS m,
  MessageVotes AS mv
WHERE
  mv.messageId = m.id
GROUP BY
  m.id, m.messageText /* here you need to place every field you `select` from Message */
ORDER BY
  SUM(mv.voteValue) DESC

甚至更好:

SELECT
  m.id,
  m.messageText,
  SUM(mv.voteValue) AS votes
FROM
  Message AS m
  LEFT JOIN MessageVotes AS mv ON mv.messageId = m.id
GROUP BY
  m.id, m.messageText
ORDER BY
  SUM(mv.voteValue) DESC

请参阅:

答案 3 :(得分:0)

请尝试以下查询,您错过了分组条款。

    SELECT g.message, 
        g.date, 
        g.ip, 
        g.name, 
        g.website, 
        g.id 
    FROM guestbook_message AS g 
    JOIN m_votes AS v ON g.id = v.vid 
    WHERE g.deleted = 0 
        AND v.messageid = $mid 
        AND g.date > DATE_SUB(NOW(), INTERVAL 1 DAY) 
    GROUP BY g.message, 
        g.date, 
        g.ip, 
        g.name, 
        g.website, 
        g.id
    ORDER BY SUM(v.votes) DESC;