【问题标题】:MySQL check two columns for value but with a preferred column resultMySQL 检查两列的值,但具有首选列结果
【发布时间】: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 sql sql-order-by case sql-limit


    【解决方案1】:

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

    【讨论】:

    • 感谢您提供的解决方案,该解决方案适用于初始测试。我对使用 LIMIT 犹豫不决,因为我相信它会否定索引,但查询似乎以不错的速度运行
    • 欢迎@Martin!处理 1 或 2 条记录,不用担心limit 的性能...
    猜你喜欢
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多