Mysql group_concat of repeated keys and count of repetition of multiple columns in 1 query ( Query Optimization )

前端 未结 3 626
夕颜
夕颜 2021-01-19 03:00

This question is regarding query optimization to avoid multiple call to database via PHP.

So Here is scenario, I have two tables one contains information you can cal

3条回答
  •  攒了一身酷
    2021-01-19 03:17

    Judging from your quote it seems to me you want to do something like this (SQLfiddle):

    SELECT
      m.info1,
      m.info2,
      COUNT(DISTINCT CONCAT(m.key1, ' ', m.key2)) key_count,
      GROUP_CONCAT(DISTINCT CONCAT(m.key1, ' ', m.key2) ORDER BY m.key1, m.key2) key_pairs,
      COUNT(DISTINCT p.serial) serial_count,
      GROUP_CONCAT(DISTINCT p.serial ORDER BY p.serial) serials,
      COUNT(DISTINCT p.product_data) data_count,
      GROUP_CONCAT(DISTINCT p.product_data ORDER BY p.product_data) product_data
    FROM
      main_info m INNER JOIN
      product1 p ON p.key1 = m.key1 AND p.key2 = m.key2
    WHERE
      p.serial < 10
    GROUP BY
      m.info1,
      m.info2
    

    Count distinct values and list them, is this correct? You can't just group by info1, info2 and also have columns for key1 or key2 in the result (e.g. min(key1) or max(key2) would work). I adjusted this in the query above, although it is quite different from your result it might be what you actually need, maybe with a few changes.

提交回复
热议问题