Mysql 查询与带有 group_concat 的子查询并且不起作用
我的查询有一些问题,似乎不适用于 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
问题只是“catstring”列仅包含子查询中找到的第一项,但如果我替换
WHERE cid IN (n.category)
为
WHERE cid IN (19,18,3)
它,它工作得很好,但正如你所看到的这不是动态的 你知道为什么 n.category 仅限于一项吗?
我不知道你是否需要这个,但是表格的综合结构就是
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
我得到的结果和我想要的
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 have some problems with a Query seem IN dosen't work with Group_concat, that is what i wrote
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
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?
idk if u need that but a sintetic strucure of tables is
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我创建了您的测试数据并将 IN() 替换为另一个函数。它给出的正是您想要的结果:
结果是:
I created your test data and replaced the IN() with another function. It gives exactly the results you want:
Result is: