[英]left join mysql issue
This is my query: 这是我的查询:
SELECT *
FROM (
SELECT users.id, users.name, users.gender
users.gender_preference, users.about_me
FROM `users`
LEFT JOIN users_purchase ON users.id = users_purchase.user_id
WHERE users.id != 20
AND users.status = 1
AND users.birthdate <= '1996-03-18' AND users.birthdate >= '1934-03-18' AND users.gender = '2'
GROUP BY users.id
) AS myTable
I have another table that has this fields: 我有另一个包含此字段的表:
id (primary),theBlocker, whoToBlock
I need to remove from my query results the users ('whoToBlock') that the blocker ('theBlocker') blocked. 我需要从我的查询结果中删除阻止程序('theBlocker')阻止的用户('whoToBlock')。 Any idea?
任何想法?
SELECT *
FROM (
SELECT users.id, users.name, users.gender
users.gender_preference, users.about_me
FROM `users`
LEFT JOIN users_purchase ON users.id = users_purchase.user_id
LEFT JOIN OTHERTABLE ON whoToBlock = users.id
WHERE users.id != 20
AND users.status = 1
AND users.birthdate <= '1996-03-18'
AND users.birthdate >= '1934-03-18'
AND users.gender = '2'
AND OTHERTABLE.theBlocker IS NULL
GROUP BY users.id
) AS myTable
I am assuming whoToBlock maps to your user.id and theBlocker is a boolean. 我假设whoToBlock映射到你的user.id并且theBlocker是一个布尔值。 Edit these conditions accordingly
相应地编辑这些条件
I am a little unclear on who is blocking whom. 关于谁阻挡了谁,我有点不清楚。 Let me assume, for your example, that you want to exclude any users blocked by user
20
. 举例来说,假设您要排除用户
20
阻止的任何用户。 A simple way to add this to your query is in the where
clause: 将此添加到查询的简单方法是在
where
子句中:
SELECT u.id, u.name, u.gender, u.gender_preference, u.about_me
FROM `users` u LEFT JOIN
users_purchase up
ON u.id = up.user_id
WHERE u.id <> 20 AND
u.status = 1 AND
u.birthdate <= '1996-03-18' AND
u.birthdate >= '1934-03-18' AND
u.gender = '2' and
NOT EXISTS (select 1
from blockers b
where b.theBlocker = 20 and b.whomToBlock = u.id
)
GROUP BY users.id;
Note that I also removed the additional layer of subqueries and added table aliases to make the query more readable. 请注意,我还删除了附加的子查询层并添加了表别名,以使查询更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.