dtbiszu7724 2012-05-17 17:50
浏览 56
已采纳

Mysql - 如果找不到特定记录,则抓取默认记录

Using MySQL and php how would I, in a single query, grab all results matching a certain query but if no results found it then finds all the default results? For example I have this query:

SELECT * FROM table1 WHERE typeid = 5

If no results are found from the query below then I want to find all results from table1 with the typeid of 1:

SELECT * FROM table1 WHERE typeid = 1

How can I do that in a single query? If I try the following query I get both 5 and 1:

SELECT * FROM table1 WHERE typeid = 5 OR typeid = 1

All I want to to is query table1 for all records assigned with typeid of 5, if no results found then get all results assigned to typeid = 1 in a single query. How can I do that? Or do I have to have 2 queries?

EDIT

I need this for multiple records returned, not a single record.

  • 写回答

3条回答 默认 最新

  • dongshie8450 2012-05-17 18:07
    关注
    SELECT *
    FROM   table1
    WHERE  typeid = IF((SELECT COUNT(*) FROM table1 WHERE typeid = 5), 1, 5);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法