开发者

Select rows from table but retrieve override where possible

Given the table:

id    domain        name    value
----------------------------------
1     NULL          a       v1
2     example.com   a       v2
3     example.net   a       v3
4     NULL          b       v4
5开发者_高级运维     example.net   b       v5
6     example.com   c       v6
7     example.com   d       v7
8     NULL          d       v8

How can I run a query which will retrieve the following results for domain = "example.com"? Note that NULL domain is assumed when value is not specified for domain.

name    value
--------------
a       v2
b       v4
c       v6
d       v7

And for domain = "example.net":

name    value
--------------
a       v3
b       v5
d       v8


Like so

(select name, value
from <your_table_name>
where domain = 'example.com')
union
(select name, value
from <your_table_name>
where domain is null
and name not in
    (select name
    from <your_table_name>
    where domain = 'example.com'))


Aggregate over the maximum of value:

SELECT name, MAX(value) AS max_value FROM thetable GROUP BY name;
SELECT name, MAX(value) AS max_value FROM thetable WHERE domain = "example.net" GROUP BY name;


Why not to use simple select SELECT name,value FROM table_name WHERE domain="example.net" ORDER BY name ?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜