仅从一个表中选择用户,除非不在另一个表中 [英] Select users from one table only if not in another
本文介绍了仅从一个表中选择用户,除非不在另一个表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们有两个表:
-用户-
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
这是实际代码的简化示例,可以使问题对以后的读者有用/可读.
相关问题: MySQL:仅从一个表中选择电子邮件,如果不在另一个表中?
推荐答案
像这样吗?
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.
这篇关于仅从一个表中选择用户,除非不在另一个表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文