【问题标题】:Using DISTINCT with FIND_IN_SET将 DISTINCT 与 FIND_IN_SET 一起使用
【发布时间】:2017-02-16 00:24:59
【问题描述】:

我想同时选择 DISTINCT(p.ptype) 如果 p.ptype 不在 c.ptype 的集合中,我也想获取 c.category

数据库表:p

id   ptype
1    Shirts
2    Cups
3    Shirts
4    Mugs

数据库表:c

id  category  ptype
1   Test      Pants, Shirts, TShirts
2   Test1     Cups, Mats, Rugs

我试过的SQL命令如下

SELECT DISTINCT(p.ptype), IF(FIND_IN_SET(p.ptype, c.ptype), c.category,'') as category
FROM p, c 

这会输出 p.ptype 两次设置。一次是空白的 c.category 字段,一次是填充的 c.category。

但是想要的输出如下

ptype    category
Shirts   Test
Cups     Test1
Mugs

【问题讨论】:

    标签: mysql select distinct find-in-set


    【解决方案1】:

    尝试在p 表中的ptype 上执行显式LEFT JOIN,该表出现在c 表的CSV 列表中:

    SELECT DISTINCT p.ptype, COALESCE(c.category, '') AS category
    FROM p
    LEFT JOIN c
        ON FIND_IN_SET(p.ptype, c.ptype) > 0
    

    在您的原始查询中,正在执行交叉联接。这会在两个表的记录之间生成所有可能的组合。使用交叉连接很难得出正确答案,因此最好使用左连接。

    演示在这里:

    SQLFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-18
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多