0

I have table Foo like:

id,
bar_1,
bar_2,
bar_3

bar1, bar2, bar3 could contain foreign key (integer) or null. I want to select all rows from Foo, where ids 2, 4 (both) are present in any two of bar1, bar2, bar3.

Simple way would be to make lot of OR's, but I believe there's simplier way.

I thought about something like

SELECT * FROM foo WHERE (2,4) IN ARRAY(bar_1, bar_2, bar_3)

Is it possible?

5
  • what is bar_1? a number? Commented Apr 17, 2015 at 13:14
  • Integer. Updated the question Commented Apr 17, 2015 at 13:15
  • SELECT * FROM foo WHERE id in (2, 4) ? Commented Apr 17, 2015 at 13:16
  • You misunderstood my question. (2, 4) should be present in any subset of bar_1, bar_2, bar_3, for example bar_1 = 2 and bar_2 = 4 or bar_1 = 4 and bar_2 = 2 or bar_1 = 4 and bar_3 = 2 and so on (cartesian) Commented Apr 17, 2015 at 13:18
  • ahh, I see now, bar_1, bar_2, bar_3 are columns, ok Commented Apr 17, 2015 at 13:19

3 Answers 3

3

Well, almost :-)

SELECT * FROM foo 
WHERE 2 IN (bar_1, bar_2, bar_3)
  AND 4 IN (bar_1, bar_2, bar_3);
Sign up to request clarification or add additional context in comments.

Comments

0
SELECT * FROM foo WHERE bar_1 IN (2,4) OR bar_2 IN (2,4) OR bar_3 IN (2,4)

3 Comments

what if bar_1 = 2, bar_2 = 2 and bar_3 = 2?
both 2 and 4 should exists... in this case only 2 exists
uups, yes you right. @ThorstenKettner has the write answer isn't it
0

I think..no.. use code like this

select * from foo where ((concat(bar_1,',',bar_2)='2,4') || (concat(bar_2,',',bar_3)='2,4') || (concat(bar_3,',',bar_1)='2,4') || (concat(bar_2,',',bar_1)='2,4') || (concat(bar_3,',',bar_2)='2,4') || (concat(bar_1,',',bar_3)='2,4'))

4 Comments

what if bar_1 = 4, bar_2 = 2 ?
Please check the query again..the condition has been concatenated as bar_2,',',bar_1='2,4'
if it fulfills the answer then ok... please explain mess by concatenation after that concatenation will be removed from MySQL
any reason to concat, and do additional operations, when you can just compare?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.