按匹配记录排序

时间:2014-10-25 10:23:23

标签: performance postgresql

首先,对不起标题,我不知道如何命名这个问题。

基本上,我正在根据位置和类别编写基本搜索引擎。

我有一个表事件,一个表events_categories和一个表类别。对象具有列城市和列状态

一个事件拥有并属于许多类别,一个类别拥有并属于许多事件。

我目前有以下查询:

select 
*
from events
LEFT OUTER JOIN "events_categories" 
ON "events_categories"."event_id" = "events"."id" 
LEFT OUTER JOIN "categories" 
ON "categories"."id" = "events_categories"."category_id" 
WHERE "categories"."id" = 2 
OR "categories"."id" = 3
order by city!='Paris', state!='TX'

它有效,但我想根据匹配的类别数量来订购我的结果,我也有重复的行。我想删除它们

这是the sqlfiddle I use

预期结果应为:

  • meetup#2
  • meetup#1
  • meetup#4
  • meetup#16
  • meetup#5
  • meetup#7
  • meetup#8

2 个答案:

答案 0 :(得分:2)

这似乎做你想要的。虽然最后两行可能不是您需要的顺序,但这是因为这两行的所有排序条件的值都相同:

select events.id as event_id, 
       events.name as event_name,
       events.city,
       events.state,
       categories.id as category_id,
       categories.name as category_name,
       count(*) over (partition by events.id) as cat_count
from events
  LEFT JOIN events_categories ON events_categories.event_id = events.id
  LEFT JOIN categories ON categories.id = events_categories.category_id 
WHERE categories.id IN (2,3)
order by city <> 'Paris', 
         state <> 'TX',
         cat_count desc;

SQLFiddle:http://sqlfiddle.com/#!12/6c7a5/1

答案 1 :(得分:1)

要按匹配类别的数量排序,您可以group by事件名称,然后按count(*) desc排序:

select  e.name
,       count(*)
from    events e
join    events_categories ec
on      ec.event_id = e.id
join    categories c
on      c.id = ec.category_id
where   c.id in (2,3)
group by
        e.name
order by 
        count(*) desc

Example at SQL Fiddle.