dousi4950 2014-10-28 21:42
浏览 15
已采纳

需要一个mysql查询推荐

Assuming this is possible, I'm looking for a method(MYSQL query) to join tables where none of the values returned are duplicated. I would like to join three tables (A, B, C). The common column among the three tables is the user_id. The user_id will be unique in Table A - users will only have one row/record in Table A. However, the user_id will not be unique in Tables B & C - users may have several records/rows in both tables B & C. I've tried INNER, LEFT, and RIGHT JOINS, as well as UNION However, it duplicates the results from Table A to match with the results from Table B & C.

Row 1:    Value1(from A)        Value1(from B)        Value1(from C)
Row 2:    Value1(from A)        Value2(from B)        Value2(from C)  
Row 3:    Value1(from A)        Value3(from B)        Value3(from C)

I want to avoid this. Instead I would prefer:

Row 1:    Value1(from A)        Value1(from B)        Value1(from C)
                                Value2(from B)        Value2(from C)  
                                Value3(from B)        Value3(from C)
Row 2:    Value2(from A)        Value1(from B)        Value1(from C)
                                Value2(from B)        Value2(from C)  
                                Value3(from B)        Value3(from C)

Thanks in advance for any help.

  • 写回答

1条回答 默认 最新

  • dou6495 2014-10-28 22:43
    关注

    If your main interest is in having each row return all of the other values in B and C, and you aren't fussed about the number of columns, then the following might be useful:

    SELECT A.F1, GROUP_CONCAT(B.F1) AS all_b_F1, GROUP_CONCAT(C.F1) AS all_c_F1 FROM A INNER JOIN B USING (user_id) INNER JOIN C USING (user_id) ORDER BY A.F1;

    Note that I've made up field names since you fidn't specify them. You can add additional GROUP_CONCAT columns for other fields in B and C or alternatively CONCAT or CONCAT_WS them together in place of B.F1 in current query.

    Depending on what you want to do with the results this query might be good enough. For example, you could explode all_b_F1 in PHP to get the indiividual values, or export the query results from MySQL to a csv using FIELDS ENCLOSED BY '' so that each value in B and C gets their own cell when the csv is imported into Excel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题