我有这样的多个查询:
select id,name from phonebook WHERE (name='') AND (Tag ='') AND Country= '';
select id,name from phonebook WHERE (name='') AND Country= '';
select id,name from phonebook WHERE (tag='') AND Country= '';
我想在一个查询中加入它们(按此顺序)。
EIDT
我想在每个查询中放置顺序(不是全部):
select id,name from phonebook WHERE (name='') AND (Tag ='') AND Country= '' order by points;
所以在每个查询中获得更高分的人将是第一个
答案 0 :(得分:1)
select id, name, case when name='' and Tag ='' then 'all_empty'
when name='' then 'name_empty'
when Tag ='' then 'tag_empty'
end as result
from phonebook
WHERE Country= '' and (name='' or Tag ='')
order by result
答案 1 :(得分:1)
如果您想加入多个查询的结果,或者如果您想要实现您的解决方案,您可能正在寻找工会,请继续上述答案(但需要注意订单):
select id,name from phonebook WHERE (name='') AND (Tag ='') AND Country= '' UNION
select id,name from phonebook WHERE (name='') AND Country= '' UNION
select id,name from phonebook WHERE (tag='') AND Country= '';
正如 MatBailie 在评论中所建议的,如果您希望重复导致每个查询都保留,请使用UNION ALL
代替UNION
。
MatBailie :UNION
将搜索结果并删除重复项。 UNION ALL
甚至没有做出这种尝试。在这种情况下,我们事先知道三个查询没有相同的结果,因此UNION ALL
将删除一些冗余的CPU工作量。此外,UNION
可能会导致排序发生变化(重复数据删除),而UNION ALL
不会(在我曾经使用过的RDBMS上)。
对于您的订购,这里有两种口味
SELECT * FROM
(
select id,name from phonebook WHERE (name='') AND (Tag ='') AND Country= '' order by Points
) DUMMY_ALIAS1
UNION ALL
SELECT * FROM
(
select id,name from phonebook WHERE (name='') AND Country= '' order by Points
) DUMMY_ALIAS2
UNION ALL
SELECT * FROM
(
select id,name from phonebook WHERE (tag='') AND Country= '' order by Points
) DUMMY_ALIAS3
OR
select id,name, points from phonebook WHERE (name='') AND (Tag ='') AND Country= '' UNION
select id,name, points from phonebook WHERE (name='') AND Country= '' UNION
select id,name, points from phonebook WHERE (tag='') AND Country= '' order by Points;