简体   繁体   English

使用group_concat和子查询的MySQL查询无法正常工作

[英]Mysql Query with Subquery with group_concat and in dosen't work

i have some problems with a Query seem IN dosen't work with Group_concat, that is what i wrote 我在查询中遇到一些问题似乎无法与Group_concat一起使用,这就是我写的

SELECT category, (
    SELECT GROUP_CONCAT( DISTINCT `short` SEPARATOR ', ' )
    FROM `ods_category` 
    WHERE cid IN (n.category) 
    ORDER BY cid
) AS catstring
FROM ods_news AS n

the problem is just the column "catstring" containe only 1st item found in subquery but if i replace 问题只是列“ catstring”只包含子查询中找到的第一项,但是如果我替换

WHERE cid IN (n.category) 

with

WHERE cid IN (19,18,3)

it's work well but as u can see that isn't dynamic do u know why n.category limit to just one item? 它运作良好,但是如您所见,它不是动态的,您是否知道为什么n.category只限于一项?

idk if u need that but a sintetic strucure of tables is 如果您需要的话,则为idk,但表的结构是

ods_news                          ods_category
id      | category                cid     | short
1       | 1                       1       | AA
2       | 3                       2       | BB
3       | 4,5                     3       | CC
4       | 1,2,4                   4       | DD
5       | 6                       5       | EE
6       | 2,1,6                   6       | FF

that is the results i have and what i want 那就是我得到的结果以及我想要的

results i get                     result i want
category | catstring              category | catstring
1        | AA                     1        | AA    
3        | CC                     3        | CC
4,5      | DD                     4,5      | DD,EE
1,2,4    | AA                     1,2,4    | AA,BB,DD
6        | FF                     6        | FF
2,1,6    | BB                     2,1,6    | BB,AA,FF

I created your test data and replaced the IN() with another function. 我创建了测试数据,并将IN()替换为另一个函数。 It gives exactly the results you want: 它确切地给出了您想要的结果:

SELECT category, REPLACE((
  SELECT GROUP_CONCAT( DISTINCT `short` SEPARATOR ', ' )
  FROM `ods_category` 
  WHERE FIND_IN_SET(cid, REPLACE(n.category, ' ', '')) != 0
  ORDER BY cid
), ' ', '') AS catstring
FROM ods_news AS n

Result is: 结果是:

+----------+------------+
| category | catstring  |
+----------+------------+
| 1        | AA         |
| 3        | CC         |
| 4,5      | DD,EE      |
| 1,2,4    | AA,BB,DD   |
| 6        | FF         |
| 2,1,6    | AA,BB,FF   |
+----------+------------+
6 rows in set (0.00 sec)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM