SQL - 如何根据另外两个 table 中的数据从一个 table 中 select 行?

SQL - How do I select rows from one table depending on data from two other tables?

我有一个 SQL 问题。这是一个简单的问题,但我根本不是 SQL 人。

情况是这样的,我有三张表:

CUSTOMER(
    PK(customer_id)
)

LOAN(
    PK(loan_id),
    customer_it,
    behavior_id
)

BEHAVIOR(
    PK(behavior_id),
    unpaid_number
)

// PK(x): x is a primary key.

我想 select 所有 CUSTOMERsunpaid_number >= 1

任何人都可以告诉我解决这个问题的方法吗?

谢谢

您正在寻找 INNER JOIN。像这样使用:

SELECT * FROM CUSTOMER c
INNER JOIN LOAN l ON c.customer_id = l.customer_it
INNER JOIN BEHAVIOR b ON b.behavior_id = l.behavior_id
WHERE b.unpaid_number>=1

请尝试下面的代码

SELECT c.*
FROM CUSTOMER c
INNER JOIN LOAN l
    ON l.customer_id = c.Customer_id
INNER JOIN BEHAVIOR b
    ON b.behavior_id = l.behavior_id
WHERE  unpaid_number >=1

实际上,如果您想要所有客户,您可能希望每个客户一行,无论行为中的匹配行数如何。

建议使用 existsin:

select c.*
from customer c
where exists (select 1
              from loan l join
                   behavior b
                   on b.behavior_id = l.behavior_id
              where b.unpaid_number >= 1 and
                    l.customer_id = c.customer_id
             );

如果您正在考虑使用 select distinct,这一点尤为重要。

试试这个?

SELECT LOAN.customer_it FROM LOAN
WHERE LOAN.behavior_id IN
    (SELECT BEHAVIOR.behavior_id
    from BEHAVIOR where BEHAVIOR.unpaid_number>=1)

使用内连接

SELECT c.* FROM CUSTOMER c INNER JOIN LOAN l ON l.customer_id = c.Customer_id INNER JOIN BEHAVIOR b ON b.behavior_id = l.behavior_id WHERE unpaid_number >=1