将 DISTINCT 与 FIND_IN_SET 一起使用
Using DISTINCT with FIND_IN_SET
我想 select DISTINCT(p.ptype) 同时我也想得到 c.category 如果 p.ptype 不在 [= 的集合中34=]
数据库Table:p
id ptype
1 Shirts
2 Cups
3 Shirts
4 Mugs
数据库Table: 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
尝试对 p
table 中的 ptype
进行显式 LEFT JOIN
c
table 中的 CSV 列表]:
SELECT DISTINCT p.ptype, COALESCE(c.category, '') AS category
FROM p
LEFT JOIN c
ON FIND_IN_SET(p.ptype, c.ptype) > 0
在您的原始查询中,我们进行了交叉联接。这会生成两个 table 的记录之间的所有可能组合。使用交叉连接很难得出正确答案,因此最好使用左连接。
此处演示:
我想 select DISTINCT(p.ptype) 同时我也想得到 c.category 如果 p.ptype 不在 [= 的集合中34=]
数据库Table:p
id ptype
1 Shirts
2 Cups
3 Shirts
4 Mugs
数据库Table: 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
尝试对 p
table 中的 ptype
进行显式 LEFT JOIN
c
table 中的 CSV 列表]:
SELECT DISTINCT p.ptype, COALESCE(c.category, '') AS category
FROM p
LEFT JOIN c
ON FIND_IN_SET(p.ptype, c.ptype) > 0
在您的原始查询中,我们进行了交叉联接。这会生成两个 table 的记录之间的所有可能组合。使用交叉连接很难得出正确答案,因此最好使用左连接。
此处演示: