0

我有一个具有以下结构的“项目”表:

id, person_id, active

以及带有 id 和 name 列的“people”表。

我想按最活跃的项目排序并将 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
4

2 回答 2

1

使用 Joins 这将匹配条件。按 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
于 2012-11-01T12:07:22.910 回答
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
于 2012-11-01T12:04:03.793 回答