所以我刚刚开始进入SQL编程,并且我已经开始与两个表和一个数据透视表建立多对多的关系。我将通过API发送此信息,能够在我的前端以简单的方式遍历数据将会很酷。
表格如下:
story_template
id, title, body, author
空白
id, title, description
blanks_story_template (Pivot)
id, sid, bid, position
我设法通过使用此查询获取了我需要的信息:
SELECT
st.title, st.body, st.author,
b.*,
bst.position
FROM story_template AS st
INNER JOIN blanks_story_template AS bst ON st.id = bst.sid
INNER JOIN blanks AS b ON bst.bid = b.id
ORDER BY bst.position
结果如下:
所以我想知道的是,是否可以将多行合并为一行?例如,上面的结果如下所示:
st.id, title, body, author, b.id, title, description, position
--------------------------------------------------------------
1 title body author 1, title, description, position
2, title, description, position
3, title, description, position
2 title body author 1, title, description, position
2, title, description, position
3, title, description, position
我已经研究过GROUP_CONCAT(),如果所有列都有值,那么这将是有效的,因为那时我可以将它们拆分成一个数组。但它并没有真正帮助我,因为如果blank.description
在一行中为NULL,那么我将失去属于哪个blank.id
..
这可以在查询中使用,还是我必须在使用API发送之前对其进行解析?
如果有什么看似含糊不清我道歉,如果你需要我澄清任何事情,我会很高兴这样做。
答案 0 :(得分:1)
您可以在MySQL中使用用户变量来判断一行是否与前一行的story_template
相同。您需要更改ORDER BY
,以便同一story_template
的行在一起。
SELECT IF(id = @last_st, '', id) AS id,
IF(id = @last_st, '', title) as title,
IF(id = @last_st, '', body) as body,
IF(id = @last_st, '', author) AS author,
blank_id, blank_title, description, position,
@last_st := id
FROM (
SELECT
st.id, st.title, st.body, st.author,
b.id AS blank_id, b.title AS blank_title, b.description,
bst.position
FROM story_template AS st
INNER JOIN blanks_story_template AS bst ON st.id = bst.sid
INNER JOIN blanks AS b ON bst.bid = b.id
ORDER BY st.id, b.id
) AS x
CROSS JOIN (SELECT @last_id := null) AS y