如何搜索/查询多个表以返回常见结果?

时间:2010-11-25 21:34:00

标签: sql sql-server

我正在尝试构建搜索存储过程。我想搜索多个表并返回与应用程序相关的任何内容。现在我正在使用两张桌子。 dbo.Media有5条记录,dbo.Sites有1条记录。当我运行我的查询时,我得到5个结果返回但所有行数据来自我的1个记录dbo.Sites表。这是我的SQL

SELECT  
CASE
    WHEN D.Id IS NOT NULL THEN D.Id
    WHEN M.Id IS NOT NULL THEN M.Id             
END AS Id,
CASE
    WHEN D.Id IS NOT NULL THEN D.Name
    WHEN M.Id IS NOT NULL THEN M.Title
END AS Title,
CASE
    WHEN D.Id IS NOT NULL THEN LEFT (D.[Description], 100)
    WHEN M.Id IS NOT NULL THEN LEFT (M.[Description], 100)
END AS Content,
CASE
    WHEN D.Id IS NOT NULL THEN D.WebUserId
    WHEN M.Id IS NOT NULL THEN M.WebUserId
    ELSE ''
END AS WebUserId

FROM dbo.Sites D, dbo.Media M

WHERE (D.Status = 1 AND D.Name LIKE '%wre%') OR (M.Status = 1 AND M.Title LIKE '%wre%')

1 个答案:

答案 0 :(得分:1)

SELECT Id, Name as Title, LEFT ([Description], 100) as Content, WebUserId 
FROM dbo.DiveSites
WHERE Status = 1 
    AND Name LIKE '%wre%'
UNION ALL    
SELECT Id, Title, LEFT ([Description], 100), WebUserId 
FROM dbo.Media
WHERE Status = 1 
    AND Title LIKE '%wre%'