2013-11-21 38 views
0

我想合併查詢的兩個結果通過計數得到一個排序表,以便合併兩個表和排序依據計算

我有兩個表 第一是:like_spotted 查詢

SELECT l.id as like_id, l.spotted_id as spotted_id,count(l.spotted_id) as numero_likes, 
MAX(l.createdAt) as created 
FROM sn_like_spotted l 
LEFT JOIN prof_foto f 
ON f.id = l.spotted_id 
LEFT JOIN sn_profilo p 
ON f.profilo_id = p.id 
WHERE p.id = 3 
GROUP BY l.spotted_id 
ORDER BY numero_likes DESC, created DESC 
LIMIT 0,5 

結果:

like_id spotted_id numero_likes created 
    31 223    6   2013-11-21 16:31:20 
    11 175    5   2013-11-21 17:00:35 
    23 217    2   2013-11-15 22:52:41 

二是:like_answer 查詢是

SELECT l.id as like_id, l.risposta_id as risposta_id,count(l.risposta_id) as numero_likes, 
MAX(l.createdAt) as created 
FROM sn_like_risposta l 
LEFT JOIN sn_risposte r 
ON r.id = l.risposta_id 
LEFT JOIN sn_profilo p 
ON r.profilo_id = p.id 
WHERE p.id = 3 
GROUP BY l.risposta_id 
ORDER BY numero_likes DESC, created DESC 
LIMIT 0,5 

like_id   risposta_id  numero_likes  created 
18     94    4   2013-11-21 17:00:35 
10     93    2   2013-11-20 13:30:53 
7     85    1   2013-11-14 12:16:11 
6     84    1   2013-11-14 12:15:38 

我想通過「numero_likes」命令「混合結果」whith order DESC 我可以這樣做嗎?

回答

1

是的,你可以通過使用UNION ALL

(SELECT l.id as like_id, l.spotted_id as spotted_id,null AS risposta_id , count(l.spotted_id) as numero_likes, 
MAX(l.createdAt) as created 
FROM sn_like_spotted l 
LEFT JOIN prof_foto f 
ON f.id = l.spotted_id 
LEFT JOIN sn_profilo p 
ON f.profilo_id = p.id 
WHERE p.id = 3 
GROUP BY l.spotted_id 
LIMIT 0,5) 

UNION ALL 
(SELECT l.id as like_id, null AS spotted_id,l.risposta_id as risposta_id,count(l.risposta_id) as numero_likes, 
MAX(l.createdAt) as created 
FROM sn_like_risposta l 
LEFT JOIN sn_risposte r 
ON r.id = l.risposta_id 
LEFT JOIN sn_profilo p 
ON r.profilo_id = p.id 
WHERE p.id = 3 
GROUP BY l.risposta_id 
LIMIT 0,5) 
ORDER BY numero_likes DESC, created DESC 

UNION

+1

我曾試圖使用UNION,感謝做到這一點! – Barno