我有一个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
中成功查找后应停止时,它每次都返回两行。我缺少什么;
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
消除另一个匹配项。如果只有一条记录匹配,则排序无关紧要,并且保留。