MySQL 通过关系 table 在第三个 table 中搜索

MySQL search in 3rd table through relation table

假设我有三个 table 如下:

我目前在产品列表页面上,我想要一个能够按类别名称搜索产品的功能。

select P.* 
from P
where P.id in (select group_concat(distinct R.product_id) from C join R on C.id=R.category_id where C.name like '%something%')

上面的SQL只会给我第一个匹配,但是运行括号里的查询会return多一个id。我该如何纠正?

不需要group_concat():

select P.* 
from P
where P.id in (select R.product_id
               from C join
                    R
                    on C.id = R.category_id
               where C.name like '%something%'
              );

您的查询很好,但通常应写成:

select P.*
from P join
     R
     on P.id = R.product_id join
     C
     on C.id = R.category_id
where C.name like '%something%';

如果有多个类别符合 like 条件,则此版本可能 return 重复。