如何在SQL中执行一对多搜索?

时间:2012-03-29 19:48:12

标签: sql sql-server one-to-many where

鉴于以下内容

表:

Names
Id int
Name varchar

Properties
Id int
NameId varchar
PropertyValue int

示例数据:

Names             Properties
Id  Name         Id    NameId     PropertyValue
1   Sam          1       1              1
2   Bam          2       1              2
3   Ram          3       2              1

我想搜索NameId = 1的属性表 并且应用了标准PropertyValue = 1 AND PropertyValue = 2

我做的是

SELECT dbo.Names.Id, dbo.Names.Name, dbo.PropertyValue
FROM dbo.Names
LEFT OUTER JOIN dbo.Properties on dbo.Names.Id = dbo.Properties.NameId
WHERE dbo.Names.Id = 1
AND dbo.Properties.PropertyValue IN (1,2)

IN执行OR,我需要的是AND,我该如何实现?

修改

我想要的是,当两个标准都满足时,即使它有重复的数据又返回两个不同的行,并且当两个标准中的一个不符合时,不返回任何内容

4 个答案:

答案 0 :(得分:2)

SELECT * FROM NAMES
WHERE ID IN (
  SELECT NAMEID FROM PROPERTIES 
  WHERE PROPERTYVALUE = 1 OR 
    PROPERTYVALUE = 2
  GROUP BY NAMEID
  HAVING COUNT(*) > 1)

小提琴,如果你想测试它:http://sqlfiddle.com/#!3/23365/2

答案 1 :(得分:1)

我希望这是你想要的,因为它并不完全清楚(imho)。

SELECT n.Id, n.Name, p.PropertyValue
FROM dbo.Names n
INNER JOIN dbo.Properties p on n.Id = p.NameId 
WHERE n.ID = 1
AND EXISTS(
    SELECT null FROM Properties p2
    WHERE p2.NameId=ID AND p2.PropertyValue=1
)
AND EXISTS(
    SELECT null FROM Properties p2
    WHERE p2.NameId=ID AND p2.PropertyValue=2
)

答案 2 :(得分:0)

SELECT dbo.Names.Id, dbo.Names.Name, dbo.PropertyValue
FROM dbo.Names
LEFT OUTER JOIN dbo.Properties on dbo.Names.Id = dbo.Properties.NameId
WHERE dbo.Names.Id = 1
AND dbo.Properties.PropertyValue=1
UNION
SELECT dbo.Names.Id, dbo.Names.Name, dbo.PropertyValue
FROM dbo.Names
LEFT OUTER JOIN dbo.Properties on dbo.Names.Id = dbo.Properties.NameId
WHERE dbo.Names.Id = 1
AND dbo.Properties.PropertyValue=2

答案 3 :(得分:0)

问题是您需要为每个用户操作一组行。基本上,您希望具有两个值的行的用户。试试这个:

select * from properties p1
join names n on p1.nameId = n.id
where exists (
  select 1 from properties p2
  where p1.nameId = p2.nameId and p2.propertyValue in (1, 2)
  group by p2.nameId
  having count(distinct p2.propertyValue) = 2
)

另一种选择(基于Francis')将是:

select * from properties
join names n on p1.nameId = n.id
where nameId in (
  select nameId from properties
  where propertyValue in (1, 2)
  group by nameId
  having count(distinct propertyValue) = 2
)

但我不确定哪一个会更快。