Mysql where 子句中的 returns 逗号分隔值的子查询

Mysql subquery in where clause that returns comma separated value

我不太擅长子查询,这是我的示例表。

table customers
=====================
id  | name | order_ids
1   | John | 1,2


table orders
=====================
id  | name
1   | apple
2   | orange

我正在尝试使用此查询获取订单名称,但只得到一个结果。我不确定这是否可行。

select o.name 
from orders o 
where o.id IN(
    select c.order_ids 
    from customers c 
    where c.id=1
)

您的主要工作应该放在修复您的设计上。您不应在一个字符串列中存储多个整数值。如果每个订单属于一个客户,那么客户 ID 应该存储在 orders table 中。如果一个订单可能同时属于多个客户,那么您需要一个桥 table,每个 customer/order 元组一行。

就是说:对于您当前的设计,您可以使用 find_in_set():

select o.*
from orders o
inner join customers c on find_in_set(o.id, c.order_ids)
where c.id = 1