我的表中有两列,如first_name,last_name 我需要在first_name和Last_name中都有JHON名称的数据,其顺序如
first_name last_name
Jhon Ashosh
Jhon Billa
Jhon Chowdary
Asthosh Jhon
Bandla Jhon
Mehon Jhon
像上面那样我需要输出
注意:首先我需要谁拥有first_name Jhon和last_name排序顺序
第二个first_name排序顺序,其中包含一个查询的last_name中的Jhon
答案 0 :(得分:0)
您可以尝试此操作,假设您的db表名为my_table
SELECT * FROM my_table
WHERE first_name ='Jhon' OR last_name='Jhon'
ORDER BY last_name, first_name
<强>更新强>
SELECT last_name, first_name
FROM (
SELECT 1 setNum, last_name, first_name
FROM Users
WHERE last_name = 'Jhon'
UNION ALL
SELECT 2 setNum, last_name, first_name
FROM Users
WHERE first_name = 'Jhon'
) mergedTable
ORDER BY setNum, (CASE WHEN 1 THEN first_name END), (CASE WHEN 2 THEN last_name END);
答案 1 :(得分:0)
对于您的情况,您可以使用:
select
first_name, last_name
from
table_name
where
first_name = 'Jhon' or last_name = 'Jhon'
order by
case when first_name = 'Jhon' then last_name end
,case when last_name = 'Jhon' then first_name end;
P / S:我对上述解决方案的工作原理有点困惑:
select
first_name, last_name
from
table_name
where
first_name = 'Jhon' or last_name = 'Jhon'
order by
case when first_name = 'Jhon' then 0 else 1 end
,case when first_name = 'Jhon' then last_name end
,case when last_name = 'Jhon' then first_name end;
答案 2 :(得分:0)
对于MySQL:
@Inject
对于Oracle:
ORDER BY first_name='Jhon' DESC, last_name, first_name
对于SQL Server
ORDER BY DECODE(first_name,'Jhon',0,1), last_name, first_name
对于更便携的ANSI标准解决方案:
ORDER BY IIF(first_name='Jhon',0,1), last_name, first_name
答案 3 :(得分:-1)
如果您想确保输出的顺序,那么:
然后使用通用SQL(例如,不使用CTE),您可以这样做:
SELECT first_name, last_name, 1 as name_order
FROM my_table
WHERE first_name = 'Jhon'
UNION ALL
SELECT first_name, last_name, 2
FROM my_table
WHERE last_name = 'Jhon'
ORDER BY
name_order,
first_name,
last_name