SQL 当在另一行的多行中找到 id 时,仅查询到 return 一行 table

SQL Query to return only one row when id is found in multiple rows from another table

我是 SQL 的新手,我有一个看似简单的问题,但我不知道该怎么办。

我有两个 table,一个用于付款,一个用于证书。 我想要 return 所有满足条件的证书,即它们的 public_key 出现在付款 table 中的未付款行中。我尝试使用 join,但当我只想要证书时它会 return 所有付款请求。

这是付款 table:

这是证书table:

这是我用 JOIN 尝试的结果:

SELECT * 
  FROM certificate
  WHERE created_at BETWEEN '${beginDate}' AND '${endDate}'
  LEFT JOIN payment ON certificate.public_key = payment.certificate_id;  

I want to return all certificates that fulfill the condition that their public_key is present in an unpaid row inside the payment table.

这会暗示这样的事情:

SELECT c.* 
FROM certificate c JOIN
     payment p
     ON c.public_key = p.certificate_id;
WHERE c.created_at BETWEEN ? AND ?

外部联接不是必需的,JOINFROM 子句中的 运算符

I want to return all certificates that fulfill the condition that their public_key is present in an unpaid row inside the payment table.

如果我没听错,你可以使用exists:

select c.*
from certificate c
where exists (
    select 1
    from payment p
    where 
        p.certificate_id = c.public_key
        and created_at BETWEEN :beginDate AND :endDate
        and p.status = 'unpaid'
)

请注意,根据您的问题描述,我在 payment(status) 上添加了过滤条件。

这种方法的好处是,如果 payment table 中有一个以上匹配的“未付费”行,它不会复制 certificate 行。