[英]SQL left join on condition OR other condition
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. 除了与交互表返回重复的警报ID外,这多少返回了我所不想要的信息。第一个消息说警察在该警报上发布了交互,该警报为a.user_id 0,另一个则以用户名正确返回。 Can someone help me? 有人能帮我吗?
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
在您遇到的情况下,您需要发出警报:1.表reply
所引用的用户2.表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. 这样,您就可以在SELECT
语句中显示所需的字段。
Hope this will help. 希望这会有所帮助。
You have your r and i user ID references in the where clause turning it from a left-join to an inner join. 在where子句中具有r和i用户ID引用,将其从左联接变为内部联接。 Move those conditions to the join portion, then test for NOT NULL for either of them. 将这些条件移到连接部分,然后为其中任何一个测试NOT NULL。
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 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.