[英]Search with SQL
我想使用PHP和SQL进行良好的搜索。 我正在考虑使用SQL的运算符LIKE(例如: SELECT * FROM Customers WHERE Country LIKE '%land%
'),但我希望要显示的第一个元素是以“ land”开头的元素。 我怎样才能做到这一点? 我不想对数据库执行多个查询,因为我认为这是一个坏主意(但我可能错了)。
您可以根据国家是否以land
为起点进行排序。 我猜想您正在使用MySQL,它有一个巧妙的功能:在数值上下文中引用时,将true / false转换为1/0,因此这确实很容易做到:
SELECT *
FROM Customers
WHERE Country LIKE '%land%'
ORDER BY Country LIKE 'land%' DESC
其他RDBMS可能没有这样的布尔值处理方法,但是您始终可以使用case
表达式自己实现它:
SELECT *
FROM Customers
WHERE Country LIKE '%land%'
ORDER BY CASE WHEN Country LIKE 'land%' THEN 1 ELSE 0 END DESC
我建议不要使用LIKE来实现搜索,它有很多限制。 但是,如果您的用例很简单,则可以执行以下操作:
SELECT 1 as orderby, *
FROM Customers
WHERE Country LIKE 'land%'
union all
SELECT 2, *
FROM Customers
WHERE Country LIKE '_%land%'
order by orderby
这种方法使您可以创建多个级别的排序
您正在寻找UNION运算符:
SELECT * FROM Customers
WHERE Country LIKE 'land%'
UNION
SELECT * FROM Customers
WHERE Country LIKE '%land%';
这将首先返回land
然后返回其他所有东西。 您将需要特别列出您的字段。
SELECT field1, field2, field3, etc
FROM customers
WHERE country LIKE 'land%'
UNION ALL
SELECT field1, field2, field3, etc
FROM customers
WHERE country LIKE '%land%'
AND country NOT LIKE 'land%'
或在查询的第二部分中使用子查询(如果您说customerid
ID字段)。
SELECT field1, field2, field3, etc
FROM customers
WHERE country LIKE 'land%'
UNION ALL
SELECT field1, field2, field3, etc
FROM customers
WHERE country LIKE '%land%'
AND customerid NOT IN (SELECT customerid
FROM customers
WHERE country LIKE 'land%')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.