SQL: conditioning multiple rows on an inner joined table

你。 提交于 2019-12-06 22:27:27

You can select the individual Ids who answered one of the questions, like this:

select distinct memberId where answerId = 'dogs'
select distinct memberId where answerId = 'red'

Then replace the ands with inner joins, like this:

select memberId from
(select distinct memberId where answerId = 'dogs') D
inner join
(select distinct memberId where answerId = 'red') R
on D.MemberId = R.memberId

And replace the OR with UNION, like this:

select memberId from
(select distinct memberId where answerId = 'dogs') D
inner join
(select distinct memberId where answerId = 'red') R
on D.MemberId = R.memberId
union
select memberId from
(select distinct memberId where answerId = 'cats') D
inner join
(select distinct memberId where answerId = 'green') R
on D.MemberId = R.memberId

This is exactly, as you say, a "set sintax":

Set: each indivdual select
Intersection of sets : inner join
Union of sets: union

If you need extra conditions, for example checking only answers 1 and 2, you can use a CTE with the common conditions like "answerId in (1,2)" to avoid writing this same condition in every select, making the sintax more clear.

You can also use this sintax, which is more similar to your original writing:

select memberId from members M
where 
 ( exists (select 1 from answers where answerId='dogs' and memberId=M.member Id)
   and exists (select 1 from answers where answerId='red' and memberId=M.member Id) )
  or 
 ( exists (select 1 from answers where answerId='cats' and memberId=M.member Id)
  and exists (select 1 from answers where answerId='green' and memberId=M.member Id) )
-- I select 1 instead of * or any column for performance reasons

I leave out the details of adding extra checks (answerId and so on) to make it easier to understand.

SELECT DISTINCT memberId 
FROM members
WHERE answers.questionId=1 AND answers.answerValue IN ('dogs','red')
UNION
SELECT DISTINCT memberId 
FROM members
WHERE answers.questionId=2 AND answers.answerValue IN ('cats,'green'); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!