简体   繁体   中英

mysql group_concat for left and right table

I am using group_concat function to aggregate few movements of a product which already done for right table (stockout) with left join . MySQL code is below-

SELECT
    p.serialno AS SISN,
    p.in_quantity AS INQTY, 
    SUM(IFNULL(s.out_quantity, '0')) AS OUTQTY,
        GROUP_CONCAT(
            CONCAT(
                COALESCE(IFNULL(s.out_quantity,'0'), ''),'|'
            )
        ) details
FROM stockin p LEFT JOIN stockout s 
    ON p.serialno = s.serialno
    WHERE p.productid = 'TF00123'
GROUP BY p.stockin_id, p.serialno, s.serialno

Output as follows-

+------+-------+--------+--------------------------------+
| SISN | INQTY | OUTQTY | details                        |
+------+-------+--------+--------------------------------+
| AAA1 |   500 |    740 | 300|,100|,50|,50|,20|,20|,200| |
| AAA2 |   500 |      0 | 0|                             |
| AAA3 |     1 |      3 | 1|,1|,1|                       |
| AAA3 |     1 |      3 | 1|,1|,1|                       |
| AAA1 |   200 |    740 | 300|,100|,50|,50|,20|,20|,200| |
| AAA3 |     1 |      3 | 1|,1|,1|                       |
| AAA1 |   100 |    740 | 300|,100|,50|,50|,20|,20|,200| |
+------+-------+--------+--------------------------------+
7 rows in set (0.00 sec)

Now, I want to group_concat of left table quantities in another column like details if p.serialno is same. Please check the output if i do manually-

+------+-------+------------------+--------+--------------------------------+
| SISN | INQTY | details          | OUTQTY | details                        |
+------+-------+------------------+--------+--------------------------------+
| AAA1 |   800 | 500|,200|,100|   |    740 | 300|,100|,50|,50|,20|,20|,200| |
| AAA2 |   500 | 0|               |      0 | 0|                             |
| AAA3 |     3 | 1|,1|,1|         |      3 | 1|,1|,1|                       |
+------+-------+------------------+--------+--------------------------------+
3 rows in set (0.00 sec)

Simply use

 GROUP_CONCAT(
            CONCAT(
                COALESCE(IFNULL(p.out_quantity,'0'), ''),'|'
            )
        ) details1

Like this

SELECT
    p.serialno AS SISN, 
    p.in_quantity AS INQTY, 
    GROUP_CONCAT(
            CONCAT(
                COALESCE(IFNULL(p.out_quantity,'0'), ''),'|'
            )
        ) details1
    SUM(IFNULL(s.out_quantity, '0')) AS OUTQTY,
        GROUP_CONCAT(
            CONCAT(
                COALESCE(IFNULL(s.out_quantity,'0'), ''),'|'
            )
        ) details
FROM stockin p LEFT JOIN stockout s 
    ON p.serialno = s.serialno
    WHERE p.productid = 'TF00123'
GROUP BY p.stockin_id, p.serialno, s.serialno

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM