ID ATTRID VALSTR
1771373 1 1234
1771373 3 510
1771373 7 2016
1771373 8 05
1777623 3 5003
1777623 7 2016
1777623 8 05
1778103 3 520
1778103 7 2016
1778103 8 06
我想只选择三个条件
AttrId = 3 AND ValStr = 510
AttrId = 7 AND ValStr = 2016
AttrId = 8 AND ValStr = 05
我的查询是这样的,但查询返回所有ID
SELECT *
FROM Table
WHERE ((AttrID = 3 AND ValStr ='510') OR
(AttrID = 7 AND ValStr ='2016') OR
(AttrID = 8 AND ValStr ='05')
) AND
DefID = 1375552
我想显示提供所有三个条件的结果。对于我的例子;我应该显示1771373 id但没有调节任何id。你能帮我吗?
答案 0 :(得分:5)
您可以使用HAVING子句。
此查询将使用仅包含ID
的派生表来回答所有三个条件:
SELECT t.* FROM YourTable t
INNER JOIN(SELECT s.Id FROM YourTable s
WHERE (s.AttrID = 3 AND s.ValStr ='510') OR
(s.AttrID = 7 AND s.ValStr ='2016') OR
(s.AttrID = 8 AND s.ValStr ='05')
GROUP BY s.Id
HAVING COUNT(distinct s.AttrID) = 3) t2
ON(t.id = t2.id)
答案 1 :(得分:1)
试试这个,
select id from YourTable
where ((AttrID = 3 AND ValStr ='510') OR
(AttrID = 7 AND ValStr ='2016') OR
(AttrID = 8 AND ValStr ='05')
)
group by id having count(*)=3