MySQL检查两列的值,但有首选的列结果

问题描述 投票:0回答:1

我有一个MariaDB SQL表,带有两个不同的ID行。

ID是从先前的数据库版本导入的(old_id参考是从另一个表导入的,),[[作为过渡措施搜索需要找到ID,并优先使用较旧的ID值。只能返回ONE行。

表格:

new_id(PK) | old_id | data | more_data --------------------------------------------- 1 | 34 | harge | spalt 2 | 7 | greet | sausages 4 | 852 | humbug | gertrude 6 | 13 | bloody | festivalz 7 | 412 | hello | fiddlests 8 | 3 | fraggo | piddlebiscs

new_id是主键。 

所以:

    当页面加载有ID=852时,它需要返回第4行
  • 当页面加载有ID=7时,它需要返回第2行
  • 当页面加载有ID=8时,它返回第8行(因为old_id列中不存在8)
  • ID=5调用页面时,它不返回任何内容(两列均不匹配)
  • 我尝试了什么:

    我已经尝试过各种

    qualifying方法,但是找不到正确的语法:

    (第一次尝试很愚蠢)

    尝试:

    WHERE table.old_id = :id OR (table.new_id = :id AND table.old_id != :id) #bad one. WHERE table.old_id = :id OR (table.new_id = :id AND :id NOT IN (SELECT old_id FROM table)) WHERE table.old_id = :id OR (table.new_id = :id AND table.new_id NOT IN (SELECT old_id FROM table)) -- I think equivalent to the above WHERE CASE WHEN table.old_id = :id THEN true ELSE table.new_id = :id END WHERE IF(table.old_id = :id, true, table.new_id = :id) -- I think equivalent to the above

    我的问题:

    [当找到ID时,SQL仅在new_id中被发现时返回一行,否则,当它在old_id中成功查找后应停止时,它每次都返回两行。

    我缺少什么;

  • 如何获取SQL检查old_id列,并且仅在未找到的情况下,然后检查new_id列并仅返回一个结果?我检查过的内容

    mysql
    1个回答
    2
    投票
    假设您的查询始终只返回一条记录(这就是我对您的问题的理解),则可以进行条件排序和limit 1

    select * from mytable where :id in (old_id, new_id) order by case when old_id = :id then 0 else 1 end limit 1

    如果两个记录匹配,则条件order by子句将匹配的记录放在old_id的顶部。然后,limit 1消除另一个匹配项。如果只有一条记录匹配,则排序无关紧要,并且保留。
    © www.soinside.com 2019 - 2024. All rights reserved.