嗨我正面临一个问题, 我有一种情况需要根据where子句
中匹配列的优先级从db中选择数据离。我有一张桌子
Employee: FirstName, LastName, City, State.
我想根据标准搜索员工的记录。但情况是,首先我需要获得所有四个标准(列)匹配的记录,然后是所有那些四个标准中的三个(列)匹配的记录,然后是所有那些记录中四个标准中的两个(列)匹配等......
为此,我根据情况创建动态查询,但如果搜索条件会扩展得更多,那么我需要在查询中添加许多条件,因此很难管理动态查询。那么有没有其他方法来处理这个问题?
非常感谢提前。
答案 0 :(得分:3)
这已经在SQL Server上进行了测试,但如果它没有立即起作用,应该让你对MySQL有所了解;
测试数据
IF OBJECT_ID('tempdb..#TestData') IS NOT NULL DROP TABLE #TestData
GO
CREATE TABLE #TestData (FirstName varchar(20), LastName varchar(20), City varchar(20), State varchar(20))
INSERT INTO #TestData (FirstName, LastName, City, State)
VALUES
('Jon','Snow','Winterfell','Westeros')
,('Jaime','Lannister','Riverrun','Westeros')
,('Margaery','Tyrell','Kings Landing','Westeros')
,('Cersei','Lannister','Kings Landing','Westeros')
,('Daenerys','Targaryen','Mereen','Essos')
,('Davos','Seaworth','Winterfell','Westeros')
,('Theon','Greyjoy','Mereen','Essos')
,('Tyrion','Lannister','Mereen','Essos')
,('Petyr','Baelish','Winterfell','Westeros')
使用设置为变量的搜索条件进行查询。 case
将检查我们拥有的匹配项数以及该字段的order
。
DECLARE @Variable1 varchar(20); SET @Variable1 = 'Jon'
DECLARE @Variable2 varchar(20); SET @Variable2 = 'Snow'
DECLARE @Variable3 varchar(20); SET @Variable3 = 'Winterfell'
DECLARE @Variable4 varchar(20); SET @Variable4 = 'Westeros'
SELECT
FirstName
,LastName
,City
,State
,CASE WHEN FirstName = @Variable1 THEN 1 ELSE 0 END +
CASE WHEN LastName = @Variable2 THEN 1 ELSE 0 END +
CASE WHEN City = @Variable3 THEN 1 ELSE 0 END +
CASE WHEN State = @Variable4 THEN 1 ELSE 0 END Matches
FROM #TestData
ORDER BY (
CASE WHEN FirstName = @Variable1 THEN 1 ELSE 0 END +
CASE WHEN LastName = @Variable2 THEN 1 ELSE 0 END +
CASE WHEN City = @Variable3 THEN 1 ELSE 0 END +
CASE WHEN State = @Variable4 THEN 1 ELSE 0 END
) DESC
结果为:
FirstName LastName City State Matches
Jon Snow Winterfell Westeros 4
Davos Seaworth Winterfell Westeros 2
Petyr Baelish Winterfell Westeros 2
Jaime Lannister Riverrun Westeros 1
Margaery Tyrell Kings Landing Westeros 1
Cersei Lannister Kings Landing Westeros 1
Daenerys Targaryen Mereen Essos 0
Theon Greyjoy Mereen Essos 0
Tyrion Lannister Mereen Essos 0
答案 1 :(得分:0)
您可以使用+1
条件对记录进行排名。
http://sqlfiddle.com/#!9/f65790/3
SELECT FirstName, LastName, City, State
FROM Employee
ORDER BY (FirstName = 'John')
+ (LastName='Snow')
+ (City='Winterfell')
+ (State='Nord') DESC
或者如果你需要在某个地方检查那个等级:
SELECT FirstName, LastName, City, State,
(FirstName = 'John')
+ (LastName='Snow')
+ (City='Winterfell')
+ (State='Nord') Rank
FROM employee
ORDER BY Rank DESC;