2个字段中的搜索表首先显示第一个结果

时间:2016-01-19 17:21:32

标签: sql union

我有一张名为Photos(Id,Title,Description,Date,Online)的表格。 我想按标题和描述搜索表格,但我想首先查看标题搜索的结果,然后查看描述的结果。

我尝试过普通搜索,但不知道如何将它们分开。

SELECT * FROM [Photos] 
WHERE ([Online] = 1) 
AND ([Description] like '%" + querytext + "%') 
OR ([Title] like '%" + querytext + "%') 
ORDER BY [Date] DESC, [Id] DESC

然后我尝试用UNION来做,但也没有用。

SELECT * FROM [Photos] 
WHERE ([Online] = 1) 
AND ([Description] like '%" + querytext + "%') 
UNION 
SELECT * FROM [Photos] 
WHERE ([Online] = 1) 
AND ([Title] like '%" + querytext+ "%') 
ORDER BY [Date] DESC, [Id] DESCBeto

5 个答案:

答案 0 :(得分:3)

添加一些标记行的列:

SELECT *, 1 AS Mark 
FROM [Photos] 
WHERE ([Online] = 1) 
AND ([Title] like '%" + querytext + "%') 
UNION ALL
SELECT *, 2 AS Mark 
FROM [Photos] 
WHERE ([Online] = 1) 
AND ([Description] like '%" + querytext+ "%') 
ORDER BY Mark, [Date] DESC, [Id] DESC

答案 1 :(得分:3)

只需在source上添加UNION字段,将结果放入子查询中并对子查询进行排序。

SELECT *
FROM (
    SELECT 'Description' as source, * FROM [Photos] 
    WHERE ([Online] = 1) 
    AND ([Description] like '%" + querytext + "%') 
    UNION 
    SELECT 'Title' as source, * FROM [Photos] 
    WHERE ([Online] = 1) 
    AND ([Title] like '%" + querytext+ "%') 
    ) T
ORDER BY source DESC, [Date] DESC, [Id] DESC

答案 2 :(得分:1)

您可以在CASE子句中使用ORDER BY个表达式:

SELECT *
FROM Photos 
WHERE
  Online = 1 
  AND Description like '%" + querytext + "%'
  OR Title like '%" + querytext + "%'
ORDER BY
  CASE WHEN Title like '%" + querytext + "%' THEN 1 ELSE 2 END,
  [Date] DESC,
  [Id] DESC

答案 3 :(得分:0)

SELECT *
FROM (
    SELECT 'Description' as source, * FROM [Photos] 
    WHERE ([Online] = 1) 
    AND ([Description] like '%" + querytext + "%') 
    UNION 
    SELECT 'Title' as title, * FROM [Photos] 
    WHERE ([Online] = 1) 
    AND ([Title] like '%" + querytext+ "%') 
    ) T
ORDER BY title DESC, [Date] DESC, [Id] DESC

答案 4 :(得分:-1)

试试这个:

SELECT * FROM [Photos] 
WHERE ([Online] = 1) 
AND (([Description] like '%" + querytext + "%') 
OR ([Title] like '%" + querytext + "%')) 
ORDER BY [Date] DESC, [Id] DESC

这个怎么样:

SELECT *, CASE WHEN ([Description] like '%" + querytext + "%') THEN 1 WHEN ([Title] like '%" + querytext + "%') THEN 2 END AS ord  FROM [Photos] 
WHERE ([Online] = 1) 
AND (([Description] like '%" + querytext + "%') 
OR ([Title] like '%" + querytext + "%')) 
ORDER BY [Date] DESC, [Id] DESC , ord DESC