来自另一个表的MySQL PHP订单

时间:2015-08-25 18:56:56

标签: php mysql

我有一个问题。

我有2个表,一个包含评论,另一个包括这些评论的投票。

  

我的评论表:

--------------------
comment_id | comment
     1        abc1
     2        abc2
     3        abc3
     4        abc4
--------------------
  

我的投票表:

------------------
user_id  comment_id | voted
    1          1         1  // comment 1 has the result +1 now
    2          1         1  // comment 1 has the result +2 now
    3          1         2  // comment 1 has the result +1 now
    4          4         1  // comment 4 has the result +1 now
    5          4         2  // comment 4 has the result 0 now
------------------

好吧,如果一个人喜欢一个评论,它就会被保存为“1”到“已投票”。如果一个人不喜欢评论,则会将其保存为“2”以“投票”。

$likes = $db->query('SELECT * FROM voting WHERE voted=1')->num_rows;
$dislikes = $db->query('SELECT * FROM voting WHERE voted=2')->num_rows;
$the_result = $likes-$dislikes;

例如,当5个人喜欢评论而2个人不喜欢相同的评论时,我显示的结果是“+3”。

我想用最好的结果对它们进行排序。

喜欢:显示的第一个评论将有+4,显示的第二个评论将具有+2,显示的第三个将具有-2。

我想在PHP中这样做。谢谢你的帮助。

对不起我的错误解释,这是我的第一个问题。 :(

2 个答案:

答案 0 :(得分:1)

计票:

  

仅返回comment_id和总票数:   Check the code

SELECT comment_id, SUM(
  CASE voted 
    WHEN 1 THEN 1 
    ELSE -1
   END) AS total 
FROM voting 
GROUP BY comment_id
ORDER BY total DESC;
  

返回包含投票的评论:Check the code

SELECT comment_id, comments, SUM(
  CASE voted 
    WHEN 1 THEN 1 
    ELSE -1
   END) AS total 
FROM voting
INNER JOIN comments 
  USING(comment_id)
GROUP BY comment_id
ORDER BY total DESC;
  

返回所有行:Check the code

SELECT comment_id, comments, SUM(
  CASE voted 
    WHEN 1 THEN 1 
    ELSE -1
   END) AS total 
FROM voting
RIGHT JOIN comments 
  USING(comment_id)
GROUP BY comment_id
ORDER BY total DESC;

答案 1 :(得分:1)

我会尝试以下方法:

SELECT *, 
    (count(CASE WHEN vote = 1 then 1 ELSE NULL END) - (count(CASE WHEN vote = 2 then 1 ELSE NULL END))) as RESULT 
FROM comments AS c
LEFT JOIN votes as v ON c.comment_id=v.comment_id
GROUP BY c.id
ORDER BY RESULT desc