【问题标题】:how to use select where in as all required inputs如何使用 select where in 作为所有必需的输入
【发布时间】:2016-02-03 14:18:45
【问题描述】:

假设我有一个名为 tt 且 ID 为 1,2 的表

我想搜索以下所有 1,2,3 当我使用
select id from tt where id in (1,2,3)
我得到 1 和 2 的结果

但是如果我需要显示我搜索的所有内容(如果存在)或什么都不显示怎么办?

提前谢谢你

【问题讨论】:

  • 使用如果存在,count() ... where id = 1 > 0 and count() ... where id = 2 > 0 and count(*) 。 .. where id = 1 > 0 ... 然后选择 select ... else return 'Nothing found' :)

标签: mysql sql where-clause mariadb where-in


【解决方案1】:

您可以尝试将返回的计数与您比较的值的数量进行比较,如下所示:

select id from tt
where id in (1,2,4,6)
and (select count(distinct id) from tt where id in (1,2,4,6)) = 4

当然,对于每种可能性,您都必须更改查询。对于 (1,2,3,4,5),您必须将其与 5 等进行比较。

【讨论】:

  • 而不是更改每个可能性的查询可能是他可以将 ids 加载到临时表中说“t”并将查询中的文字列表替换为“select id from t”和计数(说 4) 用“从 t 中选择 count(1)”。这对于大型列表非常实用。
  • 是的,他可以,而且可以节省一些时间,@MahdiAwadi 如果你想要 shire 的建议告诉我,我会更新我的答案
  • 谢谢@sagi,它会很棒。和 thnx shire 的建议。
  • 我找不到更好的解决方案,谢谢
  • 这是我真正的查询select hotel_room_price.id FROM hotel_room_price join hotel_room on hotel_room.id=hotel_room_price.hotel_room_id join hotel on hotel.id=hotel_room.hotel_id where hotel.city_id=2 and hotel_room_price.book_date in (1454878800,1454965200,1455051600) and (select count(distinct book_date) from hotel_room_price where book_date in (1454878800,1454965200,1455051600))=3 and hotel_room_price.last_update>1454484020121
猜你喜欢
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 2018-08-14
  • 2011-11-24
相关资源
最近更新 更多