在连接表中找到的MySQL一对多按订单排序

时间:2010-04-10 23:34:00

标签: php mysql

两张桌子:

table_a
-------
table_a_id: (primary, int)

table_b
-------
table_a_id: (index, int, from table_a)
table_b_value: (varchar)

table_a_id和table_b_value之间的一对多关系。

给出这样的查询:

SELECT DISTINCT(table_a_id) FROM table_a 
JOIN table_b ON table_a.table_a_id=table_b.table_a_id

我想按table_b中table_a_id的出现次数排序。我真的不确定如何在MySQL中写这个。

4 个答案:

答案 0 :(得分:5)

SELECT COUNT(table_b.table_a_id) AS count 
FROM table_a 
JOIN table_b ON table_b.table_a_id = table_a.id 
GROUP BY table_b.table_a_id 
ORDER_BY count DESC 

答案 1 :(得分:1)

选择             a.table_a_id,             COUNT(b.table_a_id)AS a_count     FROM table_a AS a     LEFT JOIN table_b AS b         ON a.table_a_id = b.table_a_id     GROUP BY a.table_a_id     ORDER BY a_count

答案 2 :(得分:0)

在这种情况下,为什么你需要加入表格呢?

SELECT table_a_id FROM table_b GROUP BY table_a_id order by count(table_a_id) desc

答案 3 :(得分:0)

使用您的示例

SELECT table_a_id, COUNT(*)
FROM table_b
GROUP BY table_a_id

一个真实世界的例子

如果你想要一个像这样的表:

post_id  comments_count
1        20
2        125
3        43

如果您可能需要A表中的其他信息,您可以:

select p.id, count(c.*) comments_count
from posts p
join comments c on c.post_id = p.id
group by p.id

如果您不需要A表中的任何内容,则可以简化:

select post_id, count(*)
from comments
group by post_id