2013-04-05 52 views
0

我有以下查詢:mysql命令的結果通過總的權重

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 

我如何創建這個「虛擬」列並在計算中使用另外兩個的結果?

謝謝!

回答

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` 
+0

謝謝!這工作完美:) – 2013-04-05 17:40:59

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 
+0

謝謝您的回答馬克 - 但我不能得到這個工作;它正在返回一個沒有所有必要信息的空行。儘管我設法使用了fthiella的回答。 – 2013-04-05 17:40:11