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

MySQL check two columns for value but with a preferred column result

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

ID 已从以前的数据库版本导入(old_id 引用来自另一个 table),作为过渡措施 需要进行搜索以查找 ID,优先选择较旧的 ID 值。只能 ONE 行 returned 。

Table:

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 是主键。

所以:

我尝试了什么:

我尝试了各种限定的方法,但找不到正确的语法:

(第一次尝试很傻)

已尝试:

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 时,仅在 new_id 中找到 SQL return 一行,否则 return 两行每次在 old_id 中成功找到后应该停止。

我错过了什么; 我怎样才能让 SQL 检查 old_id 列,只有在找不到时,才检查 new_id 列并且只有 return 一个结果?

我检查过的内容

假设您的查询应该总是 return 一条记录(这就是我对您问题的理解),您可以进行条件排序和 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 消除另一个匹配项。如果只有一条记录匹配,排序无关紧要,它被保留。