如何选择属性可以包含两个值的行

时间:2012-11-03 16:07:06

标签: sql

我有一个名为site_attributes的表,它看起来类似于:

siteId     attributeId     tier
-------------------------------
site1id    attribute1id    1
site1id    attribute2id    1
site1id    attribute3id    1

如何从表中选择attributeId等于attribute1id的唯一站点ID AND attributeId是否等于attribute3id?

1 个答案:

答案 0 :(得分:2)

SELECT siteId, count(*) ct
FROM TableName
WHERE attributeId IN ('attribute1id', 'attribute3id')
GROUP BY siteId
HAVING ct = 2

SELECT t1.siteId
FROM TableName t1
JOIN TableName t2 USING (siteId)
WHERE t1.attributeId = 'attribute1id'
AND t2.attributeId = 'attribute3id'