2012-01-02 125 views
0

我有這個查詢在兩個SQL表中搜索。我正在尋找一種方法來按發生情況對結果進行排序。這是我的查詢:在兩個表中搜索並按術語順序搜索

SELECT `parent_id` 
FROM wp_forum_posts 
WHERE text LIKE '%{$term1}%' 
UNION 
SELECT `id` 
FROM wp_forum_threads 
WHERE subject LIKE '%{$term1}% 

哪個是最好的方法,得到結果排序?

+0

由於任一身份證的發生?不管桌子? – xQbert 2012-01-02 21:59:22

回答

1

訣竅是首先使用UNION ALL,它保留重複(普通UNION刪除重複),然後從該結果進行選擇。此查詢應該這樣做:

select * from (
    select parent_id as mID, count(*) as cnt 
    from wp_forum_posts 
    where text like '%{$term1}%' 
    group by 1 
    UNION ALL 
    select id, count(*) 
    FROM wp_forum_threads 
    where subject like '%{$term1}% 
    group by 1) x 
order by 2, 1 
0

假設ID和parent_ID在表中不重複,否則你可以得到2行每個ID ...你想他們總結在一起,如果是的話是parent_ID和ID相關?

Select mID, cnt 
FROM 
(SELECT `parent_id` as mID, count(`parent_ID`) as cnt 
FROM wp_forum_posts 
WHERE text LIKE '%{$term1}%' 
Group by `parent_ID` 
UNION 
SELECT `id`, count(`id`) as cnt 
FROM wp_forum_threads 
WHERE subject LIKE '%{$term1}% 
GROUP BY `id`) 
Order by cnt ASC, mID 
+0

是的,id和parent_id是相同的值。 – user998163 2012-01-02 22:07:32