0

I have a little problem with my SQL-Query. In my database, there are 3 tables table1, table2, table3 with some fields. In this case only up to 3 fields (id, field1, field2) per table are relevant, i tried to keep it simple in the query below.

I have the following query:

SELECT t1.field1, t1.field2
FROM table1 t1, table2 t2, table3 t3
WHERE t3.field1 = 'param1'
    AND t3.id = t1.t3_id
    AND t1.field2 = 'param2'
    OR t1.field2 IS NULL
    AND t2.field1 = 'param3'
    AND t2.id = t1.t2_id

For some reason i always get the wrong result, so i decided to add

SELECT t2.id

and

AND t2.id = 1

to test it

SELECT t1.field1, t1.field2, t2.id
FROM table1 t1, table2 t2, table3 t3
WHERE t3.field1 = 'param1'
    AND t3.id = t1.t3_id
    AND t1.field2 = 'param2'
    OR t1.field2 IS NULL
    AND t2.field1 = 'param3'
    AND t2.id = t1.t2_id
    AND t2.id = 1

Now in my result set, there are still entries with t2.id != 1. How can i prevent this?

0

1 Answer 1

2

It's the OR that causes confusion. Put it within parentheses:

SELECT t1.field1, t1.field2, t2.id
FROM table1 t1, table2 t2, table3 t3
WHERE t3.field1 = 'param1'
    AND t3.id = t1.t3_id
    AND (t1.field2 = 'param2' OR t1.field2 IS NULL)
    AND t2.field1 = 'param3'
    AND t2.id = t1.t2_id
    AND t2.id = 1

Re-write with modern, explicit JOIN syntax:

SELECT t1.field1, t1.field2, t2.id
FROM table1 t1
JOIN table2 t2 ON t2.id = t1.t2_id
JOIN table3 t3 ON t3.id = t1.t3_id
WHERE t3.field1 = 'param1'
    AND (t1.field2 = 'param2' OR t1.field2 IS NULL)
    AND t2.field1 = 'param3'
    AND t2.id = 1
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that helped, but i have another question. I keep getting a lot of equal entries (in my case 85). Whats the best way to handle this? Add DISTINCT to the query?
Yes, use SELECT DISTINCT to remove duplicates.

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.