Reputation: 2506
Is it possible to have an OR
statement in an SQL query without having to repeat information that doesn't change? Take this as an example:
SELECT *
FROM table
WHERE a = 1
AND b = 1
AND c = 1
AND x = 1
AND y = 2
OR a = 1
AND b = 1
AND c = 1
AND x = 2
AND y = 1
This is the only way I can figure out how to do it. a,b and c do not change so I see it as illogical to have to repeat them when they stay the same. Is there any way to avoid having to repeat values that don't change when including an OR
statement?
Upvotes: 1
Views: 137
Reputation: 11911
You can use parentheses:
SELECT *
FROM table
WHERE a = 1
AND b = 1
AND c = 1
AND (x = 1 AND y=2
OR x=2 AND y = 1)
Upvotes: 2
Reputation: 17161
WHERE a = 1
AND b = 1
AND c = 1
AND (
( x = 1 AND y = 2 )
OR
( x = 2 AND y = 1 )
)
Alternative option (which is clearer IMO):
SELECT *
FROM (
SELECT *
FROM table
WHERE a = 1
AND b = 1
AND c = 1
) As a_subquery
WHERE (x = 1 AND y = 2)
OR (x = 2 AND y = 1)
Upvotes: 4
Reputation: 204766
SELECT * FROM table
WHERE a = 1 AND b = 1 AND c = 1
AND
(
(x = 1 AND y = 2) OR (x = 2 AND y = 1)
)
Upvotes: 4