Home  >  Article  >  Backend Development  >  How does MySQL query specify conditions and query additional pieces of data?

How does MySQL query specify conditions and query additional pieces of data?

WBOY
WBOYOriginal
2016-10-10 11:56:20938browse

<code>SELECT * FROM `subject` WHERE  Subject_id IN (1602509) OR  1=1 LIMIT 5
比如数据库里面有一条记录 Subject_id =1602509,我的结果集想查询出5条记录,并且包含
Subject_id =1602509这一条记录,SQL该如何写呢??

如果没有Subject_id =1602509这条记录,那么就用其他数据补齐5条记录</code>

Reply content:

<code>SELECT * FROM `subject` WHERE  Subject_id IN (1602509) OR  1=1 LIMIT 5
比如数据库里面有一条记录 Subject_id =1602509,我的结果集想查询出5条记录,并且包含
Subject_id =1602509这一条记录,SQL该如何写呢??

如果没有Subject_id =1602509这条记录,那么就用其他数据补齐5条记录</code>

<code>SELECT * FROM `subject` WHERE Subject_id IN (1602509) 
UNION 
SELECT * FROM `subject` WHERE Subject_id NOT IN (1602509) LIMIT 5</code>

Actually, this is also okay

It is best to implement it at the business layer

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn