我有以下查询:
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
如何创建此“虚拟”列并在计算中使用其他两个的结果?
谢谢!
答案 0 :(得分: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
答案 1 :(得分: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`