MySQL JOIN / GROUP_CONCAT second table?

前端 未结 2 1559
时光取名叫无心
时光取名叫无心 2020-12-17 04:56

So I have this query that works perfectly:

SELECT users.*,
GROUP_CONCAT(categories.category_name) AS categories
FROM users
LEFT OUTER JOIN user_categories ON         


        
相关标签:
2条回答
  • 2020-12-17 05:24

    It does weird things, becaue there is a cross product of certain rows. You can use the DISTINCT keyword to get only unique phone numbers:

    GROUP_CONCAT(DISTINCT phones.phone_number) AS phone_numbers,
    

    Check the documentation. Alternatively, you can get the phone numbers in another query where you would select only the phone numbers with a condition like WHERE phones.user_id IN (x, x, x, ...) (x are IDs returned from the first query).

    0 讨论(0)
  • 2020-12-17 05:42

    This happened to me, I later had to alter my query to this.

    SELECT 
       ( SELECT GROUP_CONCAT(`partnumber`) FROM `product_partnumber` AS `n` WHERE `p`.`id`=`n`.`product_id`) as `partnumbers`,
       ( SELECT GROUP_CONCAT(`oem`) FROM `product_oem` AS `n` WHERE `p`.`id`=`n`.`product_id`) as `oems`
    FROM `product` AS `p`
    

    So I had to use sub queries else I had the duplication.

    0 讨论(0)
提交回复
热议问题