内部联接2张桌子多个结果

时间:2018-12-13 19:07:41

标签: mysql sql group-by

我有2张桌子,一张用于产品,另一张用于尺寸。 它们与fk有关系,问题是当我使用内部联接时,为了没有重复的结果,我不能使用“分组依据”。 这是代码:

SELECT
sneakers.sneaker_id,
sneakers.sneaker_name,
sneakers.gender,
sneakers.description,
sneakers.price,
sizes.size,
brand_names.brand_name
FROM sneakers
INNER JOIN sizes ON sneaker_fk = sneaker_id

如果我尝试使用GROUP BY sneaker_fk,它将给出以下响应:

Error
SQL query: Documentation


SELECT sneakers.sneaker_id,sneakers.sneaker_name, sneakers.gender, sneakers.description,
                                    sneakers.price, sizes.size, brand_names.brand_name FROM sneakers
                                    INNER JOIN sizes ON sneaker_fk = sneaker_id
                                    INNER JOIN brand_names ON brand_name_fk = brand_name_id
                                    GROUP BY sneaker_fk LIMIT 0, 30
MySQL said: Documentation

#1055 - Expression #6 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sneakerstore.sizes.size' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

我在做什么错? 您是否有更好的解决方案来显示具有所有相关尺寸的一项而不显示多个结果?

希望您能尽快帮助我! 预先感谢

1 个答案:

答案 0 :(得分:0)

使用MySQL的Group_Concat()函数

MySQL GROUP_CONCAT()函数从一个组返回一个字符串,该字符串具有串联的非NULL值。

摘录自Using GROUP_CONCAT with joined tables

GROUP_CONCAT也适用于联接。

假设我们有一个餐桌课程:

SELECT
  CASE
    WHEN SPRTELE_PHONE_AREA IS NULL AND SPRTELE_PHONE_EXT IS NULL THEN SPRTELE_PHONE_NUMBER
    WHEN SPRTELE_PHONE_AREA IS NULL THEN CONCAT(SPRTELE_PHONE_NUMBER, '.', SPRTELE_PHONE_EXT)
    WHEN SPRTELE_PHONE_EXT IS NULL THEN CONCAT('(', SPRTELE_PHONE_AREA, ')', SPRTELE_PHONE_NUMBER)
    ELSE CONCAT('(', SPRTELE_PHONE_AREA, ')', SPRTELE_PHONE_NUMBER, '.', SPRTELE_PHONE_EXT)
  END
FROM vcc.sprtele;

我们还有第二张桌子预订

  | id | name |
  +—-+—————+
  | 1 | Ruby 101 |
  +—-+—————+
  | 2 | TDD for Poets |
  +—-+—————+'

结果集如下:

  | id | course_id |
  +—-+———–+
  | 7 | 1 |
  +—-+———–+
  | 8 | 1 |
  +—-+———–+
  | 9 | 1 |
  +—-+———–+
  | 10 | 2 |
  +—-+———–+
  | 11 | 2 |
  +—-+———–+


SELECT courses.name, GROUP_CONCAT(bookings.id)
FROM bookings
INNER JOIN courses ON courses.id == bookings.course_id
GROUP BY bookings.course_id;