[英]How to left join with or operator and determined only one column that match
I've search the internet for days and found no solution to my problem. 我在互联网上搜索了几天,没有找到解决我问题的方法。 I've two simple tables here: 我在这里有两个简单的表格:
TB1
tb1_id tb1_name
1 Red
2 Blue
3 Yellow
TB2
tb2_id tb2_id1 tb2_id2 tb2_type tb2_value
1 3 1 A 2
Suppose table 1 is list of users. 假设表1是用户列表。 The guy called Red want to have relationship with a guy called Yellow. 那个叫Red的家伙想和一个叫做Yellow的家伙有关系。 So he send a request. 因此,他发送了一个请求。 When Yellow accepted the request I update tb2_value to 2. 当Yellow接受请求时,我将tb2_value更新为2。
Several days later, Yellow logged in and see who he has relationship with. 几天后,Yellow登录并查看他与谁有关系。 How to do a query for this where both guys can see each other too. 如何对此进行查询,使两个人也可以看到对方。 Here's my attempt so far and it's not working: 到目前为止,这是我的尝试,但没有成功:
SELECT
tb2_id1, tb2_id2, tb2_type, tb2_value, tb1_id, tb1_name
FROM
TB2
LEFT JOIN
TB1
ON
tb2_id1 = tb1_id OR tb2_id2 = tb1_id
WHERE
(tb2_id1 = :user_id AND tb2_id2 != :user_id) OR (tb2_id1 != :user_id AND tb2_id2 = :user_id) AND tb2_type = :tb2_type AND tb2_value = :tb2_value AND RAND()<(SELECT ((15/COUNT(*))*10) FROM TB2)
ORDER BY
RAND()
LIMIT
15
Or do I do it wrong? 还是我做错了?
Thank you, 谢谢,
Try this: 尝试这个:
SELECT
TB2.tb2_id1, TB2.tb2_id2, TB2.tb2_type, TB2.tb2_value,
IF(TB2.tb2_id1 = :user_id, t2.tb1_id, t1.tb1_id) AS tb1_id, -- :user_id = 1
IF(TB2.tb2_id1 = :user_id, t2.tb1_name, t1.tb1_name) AS tb1_name -- :user_id = 1
FROM TB2
LEFT JOIN TB1 t1
ON TB2.tb2_id1 = t1.tb1_id
LEFT JOIN TB1 t2
ON TB2.tb2_id2 = t2.tb1_id
WHERE (TB2.tb2_id1 = :user_id OR TB2.tb2_id2 = :user_id) -- :user_id = 1
AND TB2.tb2_type = :tb2_type -- :tb2_type = 'A'
AND TB2.tb2_value = :tb2_value -- :tb2_value = '2'
-- RAND()<(SELECT ((15/COUNT(*))*10) FROM TB2)
ORDER BY RAND()
LIMIT 15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.