【问题标题】:MySQL search in 3rd table through relation tableMySQL通过关系表在第三个表中搜索
【发布时间】:2018-08-19 23:58:38
【问题描述】:

假设我有如下三个表:

  • PRODUCT 表 (P) 具有 ID、NAME

  • CATEGORY 表 (C) 具有 ID、NAME

  • RELATION 表 (R) 有 ID、PRODUCT_ID、CATEGORY_ID

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

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 只会给我第一个匹配,但是运行括号中的查询会返回多个 id。我该如何纠正这个问题?

【问题讨论】:

    标签: mysql sql join relation


    【解决方案1】:

    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 条件匹配,此版本可能会返回重复项。

    【讨论】:

    • 你是对的!删除它,它的工作原理!还有其他写这个查询的方法吗?
    • 非常感谢!我确实尝试了第二个 sql,但不幸的是我还需要列出每个产品所属的所有类别。我的完整 sql 是: select p.*, group_concat(distinct c.id) as category_ids from p left join r on r.product_id=p.id left join c on c.id=r.category_id where ### group by p .id ### 将是我在这个问题中寻找的查询。如果我将您的第二个解决方案放入###,那么我将无法获取每个产品的所有类别 ID。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2011-01-18
    • 2017-06-25
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    相关资源
    最近更新 更多