从表A中按表格B

时间:2017-02-10 03:12:52

标签: sql sqlite

我有两个表,“主题”(表A)和“主题投票”(表B)。每个“主题”都有多个“主题投票”。我需要从“主题”中选择行,并按相关“主题投票”的总数来排序。

在sqlite中怎么可能?我需要为此创建一个视图,还是可以通过JOIN解决?

2 个答案:

答案 0 :(得分:1)

如果您不需要投票,可以在order by中添加相关查询:

select t.*
from topics t
order by (select count(*) from topic_votes tv where t.topic = v.topic) desc;

通常,您也需要结果集中的投票数。一个简单的方法是将子查询移动到select子句:

select t.*,
       (select count(*) from topic_votes tv where t.topic = v.topic
       ) as votes
from topics t
order by votes desc;

答案 1 :(得分:0)

假设您在topics表中有PK ID,在topic votes表中有FK topic_id:

select
    t.*
from topics t
left join topic_votes v on t.id = v.topic_id
group by t.id
order by count(v.topic_id) desc;
相关问题