仅从一个表中选择用户,除非不在另一个表中
问题描述:
我们有两个表:
-用户-
id name borrower
-- ------ --------
1 Peter 1
2 John 1
3 Mark 1
4 David 0
-贷款-
id from to amount
-- ---- -- ------
1 1 2 100
我需要向用户输出彼得没有借出任何钱且借款人= 1(结果中不包括彼得)的用户,像这样:
I need to output users that Peter hasn't lent any money and that are borrowers=1 (excluding Peter from the results), like this:
id name borrower
-- ------ --------
3 Mark 1
现在我被这个查询困扰(不起作用):
Right now I am stuck with this query (doesn't work):
SELECT *
FROM `users` u
LEFT OUTER JOIN `lendings` l
ON u.`id` = l.`from`
WHERE l.`from` is null
AND u.`id` != 1
AND u.`borrower` = 1
这是实际代码的简化示例,可以使问题对以后的读者有用/可读.
答
像这样吗?
SELECT
*
FROM
users
WHERE
id NOT IN (SELECT
id
FROM
lendings)
AND borrower = 1;
您可能希望使用不同的列名,因为我相信from和to是mysql中的保留字.
You might want to use different column names as I believe from and to are reserved words in mysql.