-3

I have an SQL question. It's a simple problem, but I'm not an SQL guy at all.

Here is the situation, I have three tables:

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.

I would like to select all of the CUSTOMERs who have an unpaid_number >= 1.

Can anybody show me a way to work this around?

Thanks

Chihab
  • 403
  • 5
  • 11
  • This looks very much like homework. I agree with apomene's answer, but you could have shown what you have tried already. This is a very basic task, that is easy to figure out using a beginners tutorial. – 9DA May 03 '18 at 14:37
  • Why questions like this still receive answers? – nicecatch May 03 '18 at 15:18

5 Answers5

7

You are looking for INNER JOIN. Use like:

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
apomene
  • 14,282
  • 9
  • 46
  • 72
2

Actually, if you want all customers, you presumably want one row per customer, regardless of the number of matching rows in behavior.

That would suggest using exists or in:

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
             );

This is particularly important if you are considering using select distinct.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2

Use inner join

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

1

Please, try below code

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
Joe Taras
  • 15,166
  • 7
  • 42
  • 55
Rajat Jaiswal
  • 645
  • 4
  • 15
1

try this?

SELECT LOAN.customer_it FROM LOAN
WHERE LOAN.behavior_id IN
    (SELECT BEHAVIOR.behavior_id
    from BEHAVIOR where BEHAVIOR.unpaid_number>=1)
Joe Taras
  • 15,166
  • 7
  • 42
  • 55
Mustahsan
  • 3,852
  • 1
  • 18
  • 34