Katıldı tabloda bulunan sayısına göre birçok sipariş MySQL One

2 Cevap php

İki tablo:

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

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

Table_a_id ve table_b_value arasında birçok ilişki Bir tek.

Böyle bir sorgu Verilen:

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

Ben table_b içinde table_a_id yinelenme sayısına göre sipariş etmek istiyorum. Ben MySQL bu yazmak nasıl gerçekten emin değilim.

2 Cevap

Neden bu durumda tüm tabloları birleştirmek gerekiyor?

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

Using your example

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

A real world example

: Bir tablo gibi isterseniz

post_id  comments_count
1        20
2        125
3        43

Eğer A tablodaki diğer bilgileri gerekebilir varsa, şunları yapabilirsiniz:

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

Eğer A tablodan şeye ihtiyacınız yoksa, siz kolaylaştırabilirsiniz:

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