1

SQL 是否可以根据匹配的条件对返回的行进行不同的排序?

例如,我的网页允许输入姓名或邮政编码。该查询当前按姓氏、名字排序。太好了,除非他们输入邮政编码,否则我想按邮政编码而不是姓名对结果进行排序。那可能吗?我希望这发生在同一个查询中,而不是两个。一个潜在的问题:如果输入的值与名称和 zip 都匹配怎么办?

谢谢!

伪查询:

SELECT firstName, lastName, zip
From Users
WHERE (FirstName LIKE 'search' OR LastName LIKE 'search' OR Zip LIKE 'search')
ORDER BY LastName, FirstName
4

2 回答 2

1

由于查询是以猜测哪个字段与搜索条件匹配的方式制定的,因此您可能还想尝试猜测哪个字段匹配ORDER BY

SELECT firstName, lastName, zip
From Users
WHERE (FirstName LIKE 'search' OR LastName LIKE 'search' OR Zip LIKE 'search')
ORDER BY 
    CASE WHEN FirstName LIKE 'search' THEN FirstName ELSE NULL END
,   CASE WHEN LastName LIKE 'search' THEN LastName ELSE NULL END
,   CASE WHEN Zip LIKE 'search' THEN Zip ELSE NULL END

当然,这假定它'search'代表您传递给查询的东西,它是LIKE运算符的一个有意义的参数,即具有元字符,已正确格式化,等等。

于 2013-09-26T22:35:44.340 回答
0
SELECT firstName, lastName, zip From Users
WHERE (FirstName LIKE '%search%' OR LastName LIKE '%search%' OR Zip LIKE '%search%')
ORDER BY LastName, FirstName

如果可能,请尝试将 LIKE 替换为 = 。它提高了查询的速度。无论如何,你为什么不做一个 if-else 块?

伪代码:

if (input = name){
    SELECT firstName, lastName, zip From Users
    WHERE (FirstName LIKE '%search%' OR LastName LIKE '%search%')
    ORDER BY LastName, FirstName
}
else if (input = zipcode) {
    SELECT firstName, lastName, zip From Users
    WHERE Zip LIKE '%search%'
    ORDER BY zip
}
于 2013-09-26T22:39:36.907 回答