通过加入订购大多数商品

时间:2012-11-01 12:01:06

标签: mysql sql

我有一个'items'表,其结构如下:

id, person_id, active

和'people'表,其中包含id和name列。

我想按大多数活动项目排序,并将people.name列加入sql。

我尝试做类似的事情,但它不起作用:

SELECT people.id, COUNT(*) as items_count
FROM items, people
WHERE items.active = true AND people.id = items.person_id
GROUP BY items.person_id
ORDER BY items_count DESC

2 个答案:

答案 0 :(得分:1)

使用连接,这将符合条件。按items_count排序将为您提供最活跃的用户

Select people.id, COUNT(items.active) as items_count
FROM items
LEFT JOIN people on  people.id = items.person_id
WHERE items.active = true
GROUP BY people.id
ORDER BY items_count DESC

答案 1 :(得分:0)

   select * from (SELECT people.id, COUNT(*) as items_count
    FROM items
    left outer join people on  people.id = items.person_id
    where items.active = true
    GROUP BY items.person_id) as A
    ORDER BY A.items_count DESC