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

标签 mysql

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

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

有没有一种方法可以根据两个表中的问题 ID 获取重复项,并合并表 a 在 multiaswer 列中有值且表 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   

最佳答案

您需要在联合中保留“ALL”,以便保留该 sId、qId 分组的两行。查看您的数据,对于有问题的行对,多答案/响应要么有要么什么都没有,并且'email@domain.com'> null。如果没有 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

关于MySQL union 合并两个表中的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43946704/

相关文章:

MySQL SELECT IF 在其他表中的 ID

MySQL 通过 .csv 到 GeoMesa

php - 分页系统总是缺少 1 个结果

使用两个连接的列将 MySQL 组连接转换为 Postgres

php - 如果连接存在,mysql更改where子句

php - 打印包含一些 MySQL 记录的数组

php - 设置 LAMP 服务器,phpmyadmin 出现问题“无法加载或保存配置”

php - 存储加密的用户名/密码以在没有 OAuth 的情况下在远程网站上进行身份验证

mysql - 查找比上一年增加的百分比

cakephp - 将查询转换为 cakePHP 查找语句