1

I have the follow query:

select user_id from user_tags
where user_id = 3086533

which outputs:

enter image description here

Essentially, I want to be able to take this query, and change it to only include the user_id if both the name "master_sbx" and "phonePicked"appear.

So instead of writing a query of:

select user_id from user_tags
where user_id = 3086533

with an output of:

enter image description here

I would like to add the clause of only including user_id of only ids that have both "master_sbx" and "phonePicked" applied, so the output would just return

enter image description here

Hoping this makes sense. I'm not sure its actually possible in PostGreSQL but would love any feedback! It is piece of a larger query I am going to write.

4

1 回答 1

3

如果我理解正确,您想测试 auser_id是否(至少)出现在name = 'master_sbx'name = 'phonePicked'.

很多方法可以做到这一点。最佳选择取决于不在您问题中的信息。一种方法是EXISTS

SELECT DISTINCT user_id
FROM   user_tags
WHERE  user_id = 3086533
AND    name = 'master_sbx'
AND    EXISTS (
   SELECT 1 FROM user_tags
   WHERE  user_id = 3086533
   AND    name = 'phonePicked'
   )

另一种自加入方式:

SELECT DISTINCT u1.user_id
FROM   user_tags u1
JOIN   user_tags u2 USING (user_id)
WHERE  u1.user_id = 3086533
AND    u1.name = 'master_sbx'
AND    u2.name = 'phonePicked';

DISTINCT如果(user_id, name)是唯一的,则是多余的。

这可以看作是关系划分的特例。我们在这个相关答案中组装了一整套查询技术:
How to filter SQL results in a has-many-through relationship

于 2013-11-05T23:32:55.750 回答