Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果找不到行,mysql将返回默认行_Mysql - Fatal编程技术网

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

如果找不到行,mysql将返回默认行,mysql,Mysql,我有一个这样的桌子结构 +----+-----------+--------+ | id | attr | value | +----+-----------+--------+ | 1 | attr1 | val1 | | 2 | attr1 | val2 | | 2 | default | val3 | | 3 | default | val4 | +----+-----------+--------+ 这里,(id,attr)是

我有一个这样的桌子结构

+----+-----------+--------+
| id | attr      | value  |
+----+-----------+--------+
|  1 | attr1     | val1   |
|  2 | attr1     | val2   |
|  2 | default   | val3   |
|  3 | default   | val4   |
+----+-----------+--------+
这里,(id,attr)是主键。还有id(int)、attr(varchar)、value(varchar)

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

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

如果您想在默认属性中查找具有max id的行,并将其全部保留为max id,请尝试此操作

select t1.*
from t t1 inner join (
    select attr, max(id) id
    from t
    group by attr
) t2 on t1.attr = t2.attr
and case when t1.attr = 'default' then t2.id else t1.id end = t1.id;

实现这一点的一种方法是将两个查询与
联合起来

第一个查询获取给定属性的结果,第二个查询获取没有给定属性的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')

是的,但这就是用例,我想要一个特定的属性,所以我将提供该属性。如果该属性没有值,并且存在默认值,它应该给我一个默认值。不起作用。在my_表中插入一个
值(4,'attr2','val5')
然后重试该查询。您将在结果中注意到
(4,val5)
。然后在my_表中插入值(4,‘默认值’、‘val6’),现在您甚至可以得到id=4的两个结果。添加
和a.attr='default'
没有帮助。如果有多个默认值,则这不起作用。例如:
(1,'attr1','val1'),(2,'attr1','val2'),(2,'default','val3'),(3,'default','val4'),(4,'default','val5')它不提供id3@Potato_head啊,我明白了。
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')