从表中选择行但尽可能检索覆盖

时间:2011-07-20 15:56:32

标签: mysql sql

鉴于表格:

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

如何运行查询以检索domain =“example.com”的以下结果?请注意,如果未为域指定值,则会假定NULL域。

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

对于domain =“example.net”:

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

3 个答案:

答案 0 :(得分:2)

喜欢这样

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

答案 1 :(得分:0)

汇总超过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;

答案 2 :(得分:0)

为什么不使用简单的选择SELECT name,value FROM table_name WHERE domain="example.net" ORDER BY name