来自 table 的 Return 行,如果 ID 与另一个 table 有关系,则为该行添加字段

Return rows from a table and add field for that row if the ID has a relationship with another table

使用的数据库管理系统:Amazon Aurora

我有一个 table 存储了我所有产品的列表,我们称之为 products

+----+--------------+
| id | product_name |
+----+--------------+
| 1  | Product 1    |
+----+--------------+
| 2  | Product 2    |
+----+--------------+
|    |              |
+----+--------------+

另一个名为 redeemed_products 的 table 存储用户兑换的产品 ID。

+----+---------+------------+
| id | user_id | product_id |
+----+---------+------------+
| 1  | 1       | 1          |
+----+---------+------------+
|    |         |            |
+----+---------+------------+
|    |         |            |
+----+---------+------------+

我想检索 products 的所有行并向与 redeemed_products

有关系的行添加一个额外的字段
+----+--------------+----------+
| id | product_name | redeemed |
+----+--------------+----------+
| 1  | Product 1    | true     |
+----+--------------+----------+
| 2  | Product 2    |          |
+----+--------------+----------+
|    |              |          |
+----+--------------+----------+

这样做的目的是检索产品列表,它会显示用户已经兑换了哪些产品。我不知道我应该如何处理这个问题。

使用外连接:

select p.id, p.product_name, rp.product_id is not null as redeemed
from products p
  left join redeemed_products rp on rp.product_id = p.id;

请注意,如果 product_idredeemed_products table 中出现不止一次(例如,相同的product_id 表示多个 user_id)。

如果是这种情况,您可以使用标量子select:

select p.id, p.product_name,
       exists (select * 
               redeemed_products rp 
               where rp.product_id = p.id) as redeemed
from products p;

您没有标记您的 DBMS,但以上是标准 ANSI SQL,但并非所有 DBMS 产品实际上都支持 SELECT 列表中的布尔表达式。

一个选项是在 LEFT JOIN 查询中使用条件:

SELECT p.*, CASE WHEN r.product_id IS NOT NULL THEN 'true' END AS redeemed
  FROM products p
  LEFT JOIN redeemed_products r
    ON r.product_id = p.id