我得到了一个错误,而使用左连接与组在mysql

edqdpe6u  于 2022-12-26  发布在  Mysql
关注(0)|答案(1)|浏览(90)

我想找一个没有专辑的乐队。

    • 这是我的表结构**:
CREATE TABLE bands (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE albums (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  release_year INT,
  band_id INT NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (band_id) REFERENCES bands(id)
);
    • 这是查询:**
SELECT bands.name AS 'Band Name' ,count(albums.band_id) AS ALBUMS FROM bands 
JOIN albums ON bands.id = albums.band_id
GROUP BY albums.band_id
HAVING count(albums.band_id) = 0;
    • 错误:**
Error Code: 1055. Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'record_company.bands.name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
i86rm4rw

i86rm4rw1#

试试这个

SELECT bands.name AS 'Band Name' , COUNT(albums.id) AS ALBUMS 
FROM bands
LEFT JOIN albums ON bands.id = albums.band_id
GROUP BY bands.name
HAVING count(albums.band_id) = 0;

由于SELECT表达式中有bands.name,且该表达式带有聚合函数COUNT,因此需要GROUP BY bands.name
如果成功了告诉我?

相关问题