【发布时间】:2019-11-17 15:20:57
【问题描述】:
我有一个 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调用页面时,它不返回任何内容(任何一列中都不匹配)
我尝试了什么:
我尝试了各种限定的方法,但找不到正确的语法:
(第一次尝试是愚蠢的)
尝试:
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 get rows but prefer one column value over another 和
- using CASE in the WHERE clause
- 以及其他各种不符合该概念的;有两个成功的匹配,但匹配应按列优先。
【问题讨论】:
标签: mysql sql sql-order-by case sql-limit