在以下查询的排序语句中引用count(*)
列的正确方法是什么?
select a.*, count(*) as 'Count'
from table_a a
join table_b b
on a.id = b.id
where b.status = 1
order by ??
但是,MySQL是否要对所有记录进行两次计数,order by count(*)
工作呢? 这似乎效率低下。
order by 2
不起作用,因为它正在分解table_a中的所有列。
例如,我可以做order by 8
但是如果table_a中的列数发生变化,它会中断并需要更新。
按顺序使用别名
select a.*, count(*) as C
from table_a a join table_b b
on a.id = b.id
where b.status = 1
order by C