是否可以构建以下SQL查询

时间:2008-09-19 20:57:17

标签: sql mysql database

原始查询看起来像这样(MySQL):

SELECT * 
FROM books 
WHERE title LIKE "%text%" OR description LIKE "%text%" 
ORDER BY date

是否可以重写它(没有工会或程序),因此结果将如下所示:

  • 书籍列表,其中标题与按日期排序的查询匹配,后跟:
  • 描述符合按日期排序的查询的书籍列表

所以基本上只是给匹配标题而不是描述赋予更高的优先级。

7 个答案:

答案 0 :(得分:18)

在sql server中我会执行以下操作:

select * from books 
where title like '%text%' or description like '%text%'
order by case when title like '%text%' then 1 else 2 end, date

我不确定你是否可以在mysql中的ORDER BY中包含不在SELECT中的列,但这是我使用的原则。否则,只需在SELECT中包含派生列。

答案 1 :(得分:3)

select * from books 
where title like "%text%" or description like "%text%" 
order by date, case when title like "%text%" then 0 else 1 end

答案 2 :(得分:2)

rjk的建议是正确的方法。但请记住,此查询(带或不带联合)不能使用索引,因此它不能很好地扩展。您可能想要查看MySQL的全文索引,这将更好地扩展,允许更复杂的查询,甚至帮助结果排名。

答案 3 :(得分:0)

您可以使用案例进行排序:

order by case when title like '%text%' then 0 else 1 end

答案 4 :(得分:0)

这样的事情怎么样......

select *  
from books  
where title like "%text%"  
or description like "%text%"  
order by case when title like "%text%" then 1 else 0 end desc, date

答案 5 :(得分:0)

DECLARE @Books TABLE
(
    [ID] INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    [Title] NVARCHAR(MAX) NOT NULL,
    [Description] NVARCHAR(MAX) NOT NULL,
    [Date] DATETIME NOT NULL
)

INSERT INTO @Books
SELECT 'War and Peace','A Russian Epic','2008-01-01' UNION
SELECT 'Dogs of War','Mercenary Stories','2006-01-01' UNION
SELECT 'World At Arms','A Story of World War Two','2007-01-01' UNION
SELECT 'The B Team','Street Wars','2005-01-01' 

SELECT * FROM
(
    SELECT *, CASE WHEN [Title] LIKE '%war%' THEN 1 WHEN [Description] LIKE '%war%' THEN 2 END AS Ord
    FROM @Books
    WHERE [Title] LIKE '%war%' OR [Description] LIKE '%war%'
) AS Derived
ORDER BY Ord ASC, [Date] ASC

我相信这会给你你想要的东西,但是由于派生CASE法规中的额外工作量,它可能没有良好的性能。

答案 6 :(得分:-2)

union命令会帮助你。这些方面的东西:

SELECT *, 1 as order from books where title like '%text%'
union
SELECT *, 2 as order from books where description like '%text%'
ORDER BY order, date