这是否可以在SQL查询中使用左连接实现?

时间:2017-02-03 00:03:43

标签: sql sql-server join

我有两张桌子:

t_voucher

  • ID
  • 标题
  • description

t_used_voucher

  • ID
  • 客户id
  • date_used

我希望获得customerid

未使用的所有优惠券的结果

这在SQL或替代方法中是否可行?

最接近的,我能得到的是这样的,但我认为我不能按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

1 个答案:

答案 0 :(得分:1)

只需将其添加到on子句中:

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;