[英]Combine three SQL queries with keeping orders of the queries without duplicates
I have three queries as follows:我有以下三个查询:
select * from orders where full_name like 'Mohammed Ali%' order by g_date desc
This will gives all names starting with Mohammed Ali (10 results)这将给出所有以 Mohammed Ali 开头的名字(10 个结果)
select * from orders where full_name like '%Mohammed Ali%' order by g_date desc
All names have 'Mohammed Ali' in it (20 results)所有名字中都有“Mohammed Ali”(20 个结果)
select * from orders where full_name like '%Mohammed%Ali%' order by g_date desc
All names have Mohammed and Ali (100 results)所有名字都有 Mohammed 和 Ali(100 个结果)
I would like to get results for all three queries, but the priority for the 1st query then the 2nd, and finally, the last.我想获得所有三个查询的结果,但第一个查询的优先级然后是第二个,最后是最后一个。 I don't want duplicate results.
我不想要重复的结果。
I first did the following:我首先做了以下事情:
select * from (
select * from orders where full_name like 'Mohammed Ali%'order by g_date desc)
union
select * from (
select * from orders where full_name like '%Mohammed Ali%'order by g_date desc)
union
select * from (select * from orders where full_name like '%Mohammed%Ali%'order by g_date desc)
But, I got mixed results from the three queries:(. No duplicates - (100 results) Great!但是,我从这三个查询中得到了混合结果:(。没有重复 - (100 个结果)太棒了!
Then, I tried the following:然后,我尝试了以下操作:
select * from (
select *,0 as ord from orders where full_name like 'Mohammed Ali%')
union
select * from (
select *,1 as ord from orders where full_name like '%Mohammed Ali%')
union
select *,2 as ord from (select * from orders where full_name like '%Mohammed%Ali%')
order by ord,g_date desc
The first issue was fixed (Great).第一个问题已解决(很好)。 However, now I have duplicate results (10 + 20 + 100)
但是,现在我有重复的结果 (10 + 20 + 100)
How can I get sorted results with no duplicates?如何获得没有重复的排序结果?
The only condition that you need in the WHERE
clause is full_name LIKE '%Mohammed%Ali%'
. WHERE
子句中唯一需要的条件是full_name LIKE '%Mohammed%Ali%'
。
In the ORDER BY
clause you can sort the returned rows by boolean expressions/conditions:在
ORDER BY
子句中,您可以按 boolean 表达式/条件对返回的行进行排序:
SELECT *
FROM orders
WHERE full_name LIKE '%Mohammed%Ali%'
ORDER BY full_name LIKE 'Mohammed Ali%' DESC, -- first all names starting with 'Mohammed Ali'
full_name LIKE '%Mohammed Ali%' DESC; -- then all names containing 'Mohammed Ali'
-- all the other names will be at the bottom of the resultset
try a simpel case when尝试一个简单的案例
with orders (full_name)
as
(
select 'Mohammed Ali'
Union all select 'hMohammed Ali'
Union all select 'Mohammed Ali'
Union all select 'fMohammed Ali'
Union all select 'hMohammed fAlia'
)
select
*,
case when full_name like 'Mohammed Ali%' then 1
when full_name like '%Mohammed Ali%' then 2
when full_name like '%Mohammed%Ali%' then 3
end as ord
from
(
select * from orders where full_name like '%Mohammed%Ali%'
) x
order by ord
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.