按表中出现次数排序

时间:2012-07-17 11:54:49

标签: mysql database sorting

我有一个包含许多表的数据库..每个表都只存储了ID。现在我想做的是:

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

但我也希望通过降低发生顺序对它们进行排序。

例如,所有3个表中的ID应显示在顶部,而仅出现在一个表中的ID应位于底部。关于如何做到这一点的任何线索?

3 个答案:

答案 0 :(得分:5)

试试这个

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

答案 1 :(得分: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;

我不确定你的问题,但这可以帮助

答案 2 :(得分:-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
相关问题