Reputation: 2413
i've got a question:
In a query i need to check for replies and interactions, if these are present. i want to know which user it was that made the reply or interaction and include it in my row. I currently have this:
SELECT * FROM `alerts` a
LEFT JOIN `interactions` i ON a.alerts = i.alert_id
LEFT JOIN `reply` r ON a.alerts = r.alert_id
LEFT JOIN `users` u ON u.id = r.user_id OR i.user_id
WHERE (a.user_id = '0' AND r.user_id != '')
OR (a.user_id = '0' AND i.user_id != '')
This somewhat returns what i wan't except that the With the interaction table returns duplicate alert id, The first said that the police posted the interaction on that alert which is a.user_id 0 and the other returns correct with the user's name. Can someone help me?
Upvotes: 1
Views: 1523
Reputation: 3576
In your situation you have for an alert:
1. An user that is referenced by the table reply
2. An user that is referenced by the table interactions
As both users have a different role in your query, I suggest you the following query:
SELECT *
FROM alerts A
LEFT JOIN interactions I ON I.alert_id = A.alerts
LEFT JOIN users UI ON UI.id = I.user_id
LEFT JOIN reply R ON R.alert_id = A.alerts
LEFT JOIN users UR ON UR.id = R.user_id
WHERE A.user_id = '0'
By doing so you can then display the desired fields in your SELECT
statement.
Hope this will help.
Upvotes: 1
Reputation: 48129
You have your r and i user ID references in the where clause turning it from a left-join to an inner join. Move those conditions to the join portion, then test for NOT NULL for either of them.
SELECT *
FROM `alerts` a
LEFT JOIN `interactions` i
ON a.alerts = i.alert_id
LEFT JOIN `reply` r
ON a.alerts = r.alert_id
AND r.user_id != ''
LEFT JOIN `users` u
ON ( u.id = r.user_id
OR u.id = i.user_id )
AND i.user_id != ''
WHERE
a.user_id = '0'
AND ( NOT r.user_id IS NULL
OR NOT i.user_id IS NULL )
Upvotes: 1