无法使用具有相同列名的表进行分组

时间:2018-06-08 15:49:42

标签: mysql sql

我有这些表结构:

CREATE TABLE IF NOT EXISTS `swp`.`competition_seasons` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `competition_id` INT NOT NULL,
  `season_id` INT NULL,
  `name` VARCHAR(45) NOT NULL,
  `update_at` DATETIME NULL,
  PRIMARY KEY (`id`)
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `swp`.`competition` (
  `id` INT NOT NULL,
  `country_id` INT NULL,
  `name` VARCHAR(255) NULL,
  `category` INT NULL,
  PRIMARY KEY (`id`),
  INDEX `id_idx` (`country_id` ASC)
ENGINE = InnoDB;

所以我想选择所有可用的比赛,但问题是每个比赛都有不同的赛季,所以在最后的结果中我会得到类似的结果:

{
    "id": "1093",
    "country_id": "1",
    "category": "1",
    "competition_name": "Premier League",
    "season_name": "2018",
    "season_id": "2",
},
{
    "id": "1093",
    "country_id": "1",
    "category": "1",
    "competition_name": "Premier League",
    "season_name": "2017"
    "season_id": "3",
}

我希望返回包含以下内容的单个结果:

   {
    "id": "1093",
    "country_id": "1",
    "category": "1",
    "competition_name": "Premier League",
    "seasons": [
                  ["season_name":"2018", "season_id":"2"],
                  ["season_name":"2017", "season_id":"3"],
               ] 
   }

到目前为止我做了什么:

SELECT
    c.id, c.country_id, c.category,
    c.name AS competition_name, s.name AS season_name
  FROM competition c
  LEFT JOIN competition_seasons s ON c.id = s.competition_id
  WHERE country_id = :country_id
  GROUP BY c.name, c.id

这将返回:

  

SQLSTATE [42000]:语法错误或访问冲突:1055 SELECT列表的表达式#5不在GROUP BY子句中,并且包含非聚合列' swp.s.name'它在功能上不依赖于GROUP BY子句中的列;这与sql_mode = only_full_group_by

不兼容

2 个答案:

答案 0 :(得分:3)

我想你想要:

SELECT c.id, c.country_id, c.category, c.name AS competition_name,
       GROUP_CONCAT(s.name ORDER BY s.name) AS season_names
FROM competition c LEFT JOIN
     competition_seasons s
     ON c.id = s.competition_id
WHERE country_id = :country_id
GROUP BY c.id, c.country_id, c.category, c.name;

编辑:

您无法在MySQL中完全返回结构数组。您可以格式化字符串:

       GROUP_CONCAT(s.name, ':', s.id ORDER BY s.name) AS season_names

请注意GROUP_CONCAT()接受多个参数并将它们连接在一起。

答案 1 :(得分:0)

对行进行分组时,所有未参与组条件的列都应由任何聚合函数聚合。您可以使用min()max()avg()等。只有分组列才能显示为普通列。

您的查询应类似于:

SELECT
    c.id, 
    c.name AS competition_name, 
    max(c.country_id), 
    max(c.category),
    max(s.name) AS season_name
  FROM competition c
  LEFT JOIN competition_seasons s ON c.id = s.competition_id
  WHERE country_id = :country_id
  GROUP BY c.name, c.id