我正在使用这篇文章中建议的查询 https://stackoverflow.com/a/51816820/6822845列出我的表格内容。这工作得很好,我得到了每个部分的列表,其子部分在另一列中以逗号分隔,因此我可以分解它并将其转换为数组。我的问题是,我的部分表(在我上面链接的另一篇文章中提到)有另一个名为“sorder”的列,它保存显示顺序。我不知道为什么,但我无法每次都将列选择为 0 来输出它。
SELECT sections.sorder as sorder ,section_titel as t1,
GROUP_CONCAT(sub_section_titel) as t2
FROM sections
LEFT JOIN sub_sections ON section_id = sId
GROUP BY t1
ORDER by sorder
每次我运行它时,sorder 都显示为“0”。但它不是 0。奇怪的是,我可以读取 sub_section 表中的“iorder”列。但是主表“部分”中的“sorder”列不可访问/每次为 0。我正在使用 Mysql:
最佳答案
我创建了一个 SQLFiddle我希望它代表你的数据。在该示例中,ORDER BY sorder
工作正常。我还在 GROUP_CONCAT
中包含了一个 ORDER BY
,以便可以对小节标题进行排序。因此,对于原始查询:
SELECT section_titel as t1, GROUP_CONCAT(sub_section_titel) as t2
FROM sections LEFT JOIN sub_sections ON section_id = sId
GROUP BY t1
输出是
t1 t2
Section One SubOne,SubTwo
Section Three SubThree
Section Two (null)
但是有了新的查询:
SELECT sorder, section_titel as t1, GROUP_CONCAT(sub_section_titel ORDER BY iorder) as t2
FROM sections LEFT JOIN sub_sections ON section_id = sId
GROUP BY t1
ORDER BY sorder
输出是:
sorder t1 t2
1 Section Three SubThree
2 Section One SubTwo,SubOne
3 Section Two (null)
注意根据 Section Three
和 Section One
以及 SubTwo
和 SubOne
的值重新排序 sorder
和 iorder
。
关于PHP SQL LEFT JOIN 语句丢失一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51817626/