2013-08-23 27 views
0

我有(存储在另一个表中)一对夫妇存储在其中用户可以通过输入关键字过滤数据库表界面元素:从根据关键字另一个表中的表中选择行

表按钮:

ID Name 
1 Button1 
2 Button2 
3 Button3 

表关键词:

ButtonID Keyword 
     1 Garden 
     2 House 
     3 Garden 
     3 House 

如果用户输入Garden,分贝返回Button1 and Button3

如果用户输入House,则数据库返回Button2 and Button3

如果用户输入Garden AND House,则db仅返回Button3

最后一个是这个问题,我设法拼凑此查询:

SELECT T.ID, T.Name 
      , T.Type 
      , T.Description 
      , T.Action 
      , T.Image 
FROM Tiles T 
JOIN Keywords K 
ON T.ID=K.TileID 
WHERE K.Keyword IN ('House', 'Garden') 

不幸的是,这个查询返回所有三个按钮与任何所提供的关键字。但我只想要所有提供的关键字是Button3的元素。 查询看起来应该如何实现?

感谢很多:)

+1

在花园和住宅的情况下,什么是你在你的查询中获取输入?它是否逗号分隔? –

+0

您的关系表存在问题= =这是我的意见= x –

回答

0
declare @params table (Keyword varchar(6) primary key) 

insert into @params 
select 'House' union all 
select 'Garden' 

select 
    b.Name 
from Keywords as k 
    inner join Buttons as b on b.ID = k.ButtonID 
where k.Keyword in (select Keyword from @params) 
group by b.Name 
having count(*) = (select count(*) from @params) 

sql fiddle demo

+0

谢谢!奇迹般有效。对不起,花了我很长时间才接受你的回答:/ – Christian

0

使用相交

SELECT T.ID, T.Name, T.Type, T.Description, T.Action, T.Image FROM Tiles T JOIN Keywords K ON T.ID=K.TileID WHERE K.Keyword like 'House' 
intersect 
SELECT T.ID, T.Name, T.Type, T.Description, T.Action, T.Image FROM Tiles T JOIN Keywords K ON T.ID=K.TileID WHERE K.Keyword like 'Garden' 

这应该得到你想要的东西。

0
SELECT name 
FROM tableButtons 
WHERE tableButtons.id = tableKeywords.id AND tableButtons.id 
IN 
(SELECT tableKeywords.id 
    FROM tableKeywords 
    WHERE id IN (<insert keywords here>)) 

,你可能已经知道,在上面的语句执行的第一个查询将子查询(内选),它将返回从用户的输入匹配的关键字的所有的ID,然后这些ID的将在外部查询中使用这反过来将匹配两个表

相关问题