使用多个Group Concate Mysql

时间:2017-03-17 07:05:30

标签: mysql join group-concat

我有4张桌子

trxn_tbl:

works_id    works_date
1           3/17/2017
2           3/19/2017
3           3/18/2017

apps_txn_tbl:


id  works_id    apps_name
1   1            JoinBDApps
2   1            PMS
3   1            CADET COLLEGE
4   2            JoinBDApps
5   2            PMS
6   2            CADET COLLEGE
7   3            JoinBDApps
8   3            PMS
9   3            CMH

work_loc_trxn_tbl:

id  works_id    loc 
1   1           DC  
2   2           AITSO   
3   3           DR  

works_type_txn_tbl:

    id  works_id  works_type
    1   1         Trobleshooting
    2   1         Software Upgrade
    3   2         Trobleshooting
    4   2         License Key Update
    5   3         Trobleshooting
    6   3         License Key Update

当我运行查询时Mysql说:  MySQL说:文档

1055 - SELECT列表的表达式#3不在GROUP BY子句中,并且包含非聚合列'dcapp_db.work_loc_txn_tbl.loc',它在功能上不依赖于GROUP BY子句中的列;这与sql_mode = only_full_group_by

不兼容

但我想要这种类型:

works_id    Works_date   work_type                            appsname                                       loc
1           3/17/2017   Trobleshooting, software upgrade    JoinBDapps, PMS, CADET COLLEGE                       DR
2           3/19/2017    Trobleshooting,  License Key Update    JoinBDapps, PMS, CADET COLLEGE                   AITSO
3           3/18/2017    Trobleshooting,  License Key Update     JoinBDApps, PMS,  CMH                           DR

哪里有问题,我是否需要更改表系统或查询请求帮助我.... 我的查询是:“我的查询是:

SELECT trxn_tbl.works_id, trxn_tbl.works_date,work_loc_txn_tbl.loc,GROUP_CONCAT(works_type_txn_tbl.works_type SEPARATOR ',')as worktype,GROUP_CONCAT(apps_txn_tbl.apps_name SEPARATOR ',')as appname FROM trxn_tbl JOIN works_type_txn_tbl on works_type_txn_tbl.works_id=trxn_tbl.works_id JOIN apps_txn_tbl on apps_txn_tbl.works_id=trxn_tbl.works_id JOIN work_loc_txn_tbl on work_loc_txn_tbl.works_id=trxn_tbl.works_id GROUP BY trxn_tbl.works_id;

1 个答案:

答案 0 :(得分:0)

  1. works_id,works_date,loc需要添加到GROUP BY。
  2. 您在一个查询中使用了两个GROUP_CONCAT,然后此查询没有 足够的列到GROUP BY,因此GROUP_CONCAT有重复     内容。
  3. 试试这个:

    SELECT
        trxn_tbl.works_id,
        trxn_tbl.works_date,
        work_loc_txn_tbl.loc,
        GROUP_CONCAT(
            DISTINCT works_type_txn_tbl.works_type SEPARATOR ',' -- add DISTINCT
        ) AS worktype,
        GROUP_CONCAT(
            DISTINCT apps_txn_tbl.apps_name SEPARATOR ',' -- add DISTINCT
        ) AS appname
    FROM
        trxn_tbl
    INNER JOIN works_type_txn_tbl ON works_type_txn_tbl.works_id = trxn_tbl.works_id
    INNER JOIN apps_txn_tbl ON apps_txn_tbl.works_id = trxn_tbl.works_id
    INNER JOIN work_loc_txn_tbl ON work_loc_txn_tbl.works_id = trxn_tbl.works_id
    GROUP BY
        trxn_tbl.works_id,
        trxn_tbl.works_date,
        work_loc_txn_tbl.loc
    

    SQLFIDDLE