MySQL联合合并两个表中的重复行

时间:2017-05-12 21:25:26

标签: mysql

我希望结合两个表,其中表A(multiple_choice)包含大多数调查答案,表B(免费)仅包含文本响应答案。但是,对于某些问题,表A和B中有条目。

我当前的方法是使用UNION ALL来合并两个表中的数据,但是包含两行,我想成为一行。

有没有办法根据两个表中的问题ID获取重复项,并合并表a中列的值为 multianswer 的行,表b的列中的值为响应

以下是我的发言:

SELECT sId, qId, group_concat(multianswer), response 
FROM multiple_choice
GROUP BY sId, qId

UNION ALL

SELECT sId, qId, '' as multianswer, response 
FROM text_response 
GROUP BY sId

表:

Table A multiple_choice
sId   qId  multianswer  response
1001  1    1
1001  2    3
1001  2    4
1001  2    5                                
1001  3    6            college
1001  5    1

Table B text_response
sId   qid  response
1001  1    email@domain.com
1001  4    it is of no use to me
1001  5    another other response

期望的结果:

sId   qid  multianswer  response
1001  1    1           email@domain.com
1001  2    3,4,5
1001  3    6           college
1001  4                it is of no use to me
1001  5    1           another other response

代码结果:

sId   qid  multianswer  response
1001  1    1
1001  1                email@domain.com
1001  2    3,4,5
1001  3    6           college
1001  4                it is of no use to me
1001  5    1
1001  5                another other response   

2 个答案:

答案 0 :(得分:0)

使用运算符ALL,重复删除不起作用。只需使用UNION即可。

有关详细信息,请参阅:https://dev.mysql.com/doc/refman/5.7/en/union.html

答案 1 :(得分:0)

您需要在联合中保留“ALL”,以便为该sId,qId分组保留两行。查看您的数据,对于有问题的行对,multianswer / response是或者什么都没有,'email@domain.com'>空值。如果没有max(),它将自动从分组的第一行获取这些列的值。

所以,这可能是也可能不是最好的方法,但应该完成工作。将现有查询换行为处理分组的另一个查询。

SELECT sId, qId, max(multianswer) as multianswer, max(response) as response
FROM (
     SELECT sId, qId, group_concat(multianswer) as multianswer, response 
     FROM multiple_choice
     GROUP BY sId, qId
     UNION ALL
     SELECT sId, qId, '' as multianswer, response 
     FROM text_response 
     GROUP BY sId
) fobar
GROUP BY sId, qId
相关问题