【发布时间】:2016-08-18 14:59:00
【问题描述】:
根据评论编辑
我有 2 个表格 posts 和 categories。结构及样本数据如下:
POSTS
ID NAME DESCRIPTION CATEGORY_ID
-- ----------------- ------------------- -----------
1 For Song Lovers A post all about music 8
2 For Music Lovers About passion of music 8
3 I love songs Listing favourite songs 8
4 Rock Music ImagineDragon 6
5 Retro Music Old choice musical themes 7
CATEGORIES
ID NAME
-- -----------------
6 Artists
7 Entertainment
8 Music
我想以如下方式对记录进行排序:
- 在名称、描述和类别名称中匹配关键字的帖子首先出现,然后是
- 名称中带有匹配的关键字的帖子,描述后跟
- 帖子名称中包含匹配的关键字,后跟
- 描述中带有匹配的关键字的帖子,后跟
- 类别中具有匹配关键字的帖子
我想要的结果输出是(如果 keyword=music):
OUTPUT
---------
Post ID#2
Post ID#5
Post ID#4
Post ID#1
Post ID#3
我已经能够编写 5 个查询并将其组合成唯一的记录。但这不是优化的解决方案。这是我尝试过的:
(
SELECT "posts".* FROM "posts" INNER JOIN "categories" ON "categories"."id" = "posts"."category_id" WHERE posts.name iLIKE ('%music%') AND posts.description iLIKE ('%music%') AND categories.name iLIKE ('%music%')
+
SELECT "posts".* FROM "posts" WHERE posts.name iLIKE ('%music%') AND posts.description iLIKE ('%music%')
+
SELECT "posts".* FROM "posts" WHERE posts.name iLIKE ('%music%')
+
SELECT "posts".* FROM "posts" WHERE posts.description iLIKE ('%music%')
+
SELECT "posts".* FROM "posts" INNER JOIN "categories" ON "categories"."id" = "posts"."category_id" WHERE categories.name iLIKE ('%music%')
).uniq
我什至尝试编写单个查询,但这并没有返回我想要的结果(很明显我没有使用 GROUP OR COUNT)
SELECT posts.* FROM posts INNER JOIN categories ON categories.id = posts.category_id
WHERE (
(posts.name iLIKE ('%music%') AND posts.description iLIKE ('%music%') AND categories.name iLIKE ('%music%'))
OR (posts.name iLIKE ('%music%') AND posts.description iLIKE ('%music%'))
OR (posts.name iLIKE ('%music%'))
OR (posts.description iLIKE ('%music%'))
OR (categories.name iLIKE ('%music%')))
请建议我如何使用上述 SQL 实现相同的效果。
环境详情:
数据库:PostgreSQL
版本:postgres (PostgreSQL) 9.4.5
【问题讨论】:
-
我不知道 Postgresql,但也许您可以定义名称和描述列等以进行不区分大小写的排序规则?
标签: sql ruby-on-rails postgresql