gpt4 book ai didi

如果找不到行,mysql 返回默认行

转载 作者:行者123 更新时间:2023-11-29 01:51:15 24 4
gpt4 key购买 nike

我有一个这样的表结构

+----+-----------+--------+
| id | attr | value |
+----+-----------+--------+
| 1 | attr1 | val1 |
| 2 | attr1 | val2 |
| 2 | default | val3 |
| 3 | default | val4 |
+----+-----------+--------+

这里,(id, attr) 是主键。还有,id (int), attr (varchar), value (varchar)。

我想设计一个查询,以便对于 id 的所有不同值,我可以获取特定属性的值,如果该属性不存在但作为默认值存在,则返回该默认值。即表上方的结果,对于 attr1 将是

+----+--------+
| id | value |
+----+--------+
| 1 | val1 |
| 2 | val2 |
| 3 | val4 |
+----+--------+

最佳答案

实现此目的的一种方法是将两个查询与 UNION 组合。

第一个查询获取给定属性的结果,第二个查询获取不具有给定属性的 ID 的默认结果。

例如:

select id, value 
from your_table
where attr = 'attr1'
union
select t1.id, t1.value
from your_table t1
where t1.attr = 'default'
and not exists (select NULL from your_table t2 where t2.id = t1.id and t2.attr = 'attr1')

关于如果找不到行,mysql 返回默认行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42074443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com