开发者

Mysql SELECT and return multiple rows, but prefer one column value over another when present

So i'm looking to write a MySQL query that will return a result set that, when a particular column has a particular row value, it will return that row instead of another near duplicate row but otherwise return results like normal.

Okay, here is my table

id   name    value   another

1    name1   value1  
2    name1   value1  foo
3    name2   value2  
4    name3   value3  

and results should be (if foo is present):

id   name    value   another

2    name1   value1  foo
3    name2   value2  
4    name3   value3  

I did find this example: MySQL get rows but prefer one column value over another but couldn't figure out how to adapt it to my needs...

I hope I'm making sense! No sleep in two days ain't good for attempts at elucidation! Also I'm very sorry if this has already b开发者_运维知识库een asked, i searched for a good long time but just didn't have the vocabulary to find any results...

Thanks in advance!


SELECT
  a.*
FROM atable a
  LEFT JOIN atable b ON a.name = b.name AND a.another = 'foo'


This will filter out rows with an empty another, for which an entry with the same name and value exists that does have another.

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 <> ''
        )


This sounds like a situation where the mysql coalesce function would be handy.

Coalesce returns the first non-null parameter it's given. So you can use,

SELECT id, COALESCE(another, value) FROM MyTable;

this will return two columns, the id field and either the contents of the "another" column (if it is not null) or the contents of the "value" column.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜