问题描述
|
因此,我希望编写一个MySQL查询,该查询将返回结果集,当特定列具有特定的行值时,它将返回该行而不是另一个接近重复的行,否则将返回正常结果。
好的,这是我的桌子
id name value another
1 name1 value1
2 name1 value1 foo
3 name2 value2
4 name3 value3
结果应该是(如果存在foo):
id name value another
2 name1 value1 foo
3 name2 value2
4 name3 value3
我确实找到了这个示例:MysqL获取行,但更喜欢一个列的值,但是无法弄清楚如何使其适应我的需要...
我希望我有道理!两天没睡对澄清的尝试不利!我也很抱歉,如果已经问过这个问题,我搜索了很长时间,但没有词汇来找到任何结果...
提前致谢!
解决方法
SELECT
a.*
FROM atable a
LEFT JOIN atable b ON a.name = b.name AND a.another = \'foo\'
, 这将筛选出带有空another
的行,对于该行,存在具有another
的相同name
和value
的条目。
select *
from YourTable yt1
where not exists
(
select *
from YourTable yt2
where yt1.id <> yt2.id
and yt1.name = yt2.pname
and yt1.value = yt2.value
and yt1.another = \'\'
and yt2.another <> \'\'
)
, 这听起来像是mysql合并函数很方便的情况。
Coalesce返回给定的第一个非空参数。所以你可以使用
SELECT id,COALESCE(another,value) FROM MyTable;
这将返回两列,即id字段和\“另一个\”列的内容(如果不为null)或\“ value \”列的内容。