0

我有以下查询:

SELECT
  p.`ID`,
  (SELECT COUNT(`ID`) FROM `comments` c WHERE c.`post_id` = p.`ID`) AS `comments`,
  (SELECT COUNT(`ID`) FROM `likes` l WHERE l.`post_id` = p.`ID`) AS `likes`
FROM `posts` p

我想根据第三列对结果进行排序,将按以下方式计算:

order = comments * 6 + likes * 4

如何创建这个“虚拟”列并在计算中使用其他两个的结果?

谢谢!

4

2 回答 2

3
SELECT p.ID, comments, likes, (comments * 6) + (likes * 4) AS ordering
FROM (

    SELECT
      p.`ID`,
      (SELECT COUNT(`ID`) FROM `comments` c WHERE c.`post_id` = p.`ID`) AS `comments`,
      (SELECT COUNT(`ID`) FROM `likes` l WHERE l.`post_id` = p.`ID`) AS `likes`
    FROM `posts`
) AS p
ORDER BY ordering
于 2013-04-05T16:51:32.570 回答
1

我会这样重写你的查询:

SELECT
    p.ID,
    COUNT(DISTINCT comments.ID) as comments,
    COUNT(DISTINCT likes.ID) as likes,
    COUNT(DISTINCT comments.ID)* 6 + COUNT(DISTINCT likes.ID)* 4 as `order`
FROM
    posts p LEFT JOIN comments on p.id = comments.post_id
    LEFT JOIN likes` ON likes.`post_id` = p.`ID`
GROUP BY
    p.ID
ORDER BY
    `order`
于 2013-04-05T16:53:33.823 回答