简体   繁体   English

先显示与WHERE IN()匹配的结果,然后再显示其他结果-MYSQL

[英]Show matched results with WHERE IN() first then other results- MYSQL

I have following tables: 我有以下表格:

user 用户

id  | Name    | ...
1   | John    |
2   | Richard |
3   | Michael |

book

id  | title | author| ...
1   | ABC   |  Z    |
2   | ABM   |  X    |
3   | IJK   |  W    |
4   | MNO   |  Z    |
5   | ABQ   |  Y    |

fav_book fav_book

user_id  | book_id
1        |   5   |  
1        |   4   | 
3        |   1   | 
3        |   2   | 
3        |   5   | 

Now if John searches for a book titled Ab , I want to show his favourite book first in the search results then the others. 现在,如果John搜索一本名为Ab的书,我想先在搜索结果中显示他最喜欢的书,然后再显示其他书。

So output for John searching Ab should be 因此, John搜索Ab输出应为

id  | title
5   | ABQ
1   | ABC
2   | ABM

I've tried: 我试过了:

SELECT * FROM (
(SELECT id, title
FROM book 
WHERE id IN(5,4) AND title LIKE 'Ab%')
UNION ALL
(SELECT id, title
FROM book )
) tbl ORDER BY ???

SO how can I manipulate my order by clause to get the desired result. 因此,我如何操纵我的order by子句以获得所需的结果。 Thanks. 谢谢。

I think you just want to tweak the order by : 我认为您只想order by以下方式调整order by

SELECT id, title
FROM book 
WHERE title LIKE 'Ab%'
ORDER BY (id IN (5, 4)) DESC  -- put these first

MySQL treats a boolean like an integer in a numeric context. MySQL在数值上下文中将布尔值视为整数。 "true" has the value 1 and "false" 0; “ true”的值为1,“ false”的值为0; that is why this puts the matching ids first. 这就是将匹配ID放在首位的原因。

You can add another ORDER BY key to order the values in each subset (favorites and non-favorites): 您可以添加另一个ORDER BY键来对每个子集(收藏夹和非收藏夹)中的值进行排序:

ORDER BY (id IN (5, 4)) DESC,  -- put these first
         id

I guess you don't want to hardcode the fav books for each user. 我想您不想对每个用户的收藏夹进行硬编码。
If you want the results for user_id = 1 and search for title beginning with 'Ab' : 如果您希望user_id = 1的结果并搜索以'Ab'开头的title

select 
  id, title
from book 
where title like 'Ab%'
order by (
  case when id in (select book_id from fav_book where user_id = 1) then 0
  else 1 end
), title

See the demo 观看演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM