Kechong
Kechong

Reputation: 13

Is this achievable using left joins in SQL query?

I have two tables:

t_voucher

t_used_voucher

I want to get results for all vouchers that have NOT been used by customerid

Is this even possible in SQL or an alternative approach ?

The closest, I can get is something like this, but I don't think I can filter by customerid

SELECT
    t_voucher.id, t_voucher.title,
    t_voucher.description,
    t_used_voucher.customerid
FROM
    t_voucher
LEFT JOIN 
    t_used_voucher ON t_voucher.id = t_used_voucher.id
WHERE
    t_used_voucher.id IS NULL

Upvotes: 0

Views: 39

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269703

Just add it into the on clause:

SELECT v.id, v.title, v.description, uv.customerid
FROM t_voucher v LEFT JOIN
     t_used_voucher uv
     ON v.id = uv.id AND
        uv.customerid = @customerid
WHERE uv.id is null;

Upvotes: 1

Related Questions