2012-07-17 66 views
0

我有一個包含許多表的數據庫..並且每個表只存儲了ID。現在我想要做的是:按表中的出現次數排序

SELECT id FROM table1, table2, table3 
GROUP BY id; 

但我也想按降序排列。

例如,所有3個表中的ID應該出現在最上面,而只出現在一個表中的ID應該出現在底部。有關如何做到這一點的任何線索?

回答

3

試試這個太

select id from 
(
    SELECT id FROM table1 
    union all 
    select id from table2 
    union all 
    select id from table3 
) as t 
GROUP BY id 
order by count(id) desc 
+0

這正是我想要的!太感謝了! – tk66 2012-07-17 12:30:31

+0

不客氣 – Madhivanan 2012-07-17 12:32:17

-2
select id from 
(
    SELECT id FROM table1 
    union all 
    select id from table2 
    union all 
    select id from table3 
) as t 
GROUP BY id 
order by id desc 
1
select sum(t1.id IS NOT NULL,t2.id IS NOT NULL, t3.id IS NOT NULL) as total,t1.id from table1 as t1 join table2 as t2 on t1.id=t2.id join table3 as t3 on t3.id = t1.id order by total desc; 

我不知道你的問題,但是這可以幫助

+0

這不正是我想要的,但它給了我一推到正確的方向!謝謝! – tk66 2012-07-17 12:20:03

+0

它有一個問題..它不會照顧身份證,這是不是在table1 ..你可以在這裏發佈最終答案,我們看到:) – 2012-07-17 12:22:49

相關問題