mysql查询层次结构

时间:2014-11-19 13:56:37

标签: mysql sql

我需要帮助来查找SQL查询

CREATE TABLE album (
    id_album INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL
);

CREATE TABLE sous_album (
    id_sous_album INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    id_album INTEGER REFERENCES album(id_album)
);

CREATE TABLE photo (
    id_photo INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    nom VARCHAR(255) NOT NULL,
    id_sous_album INTEGER REFERENCES sous_album(id_sous_album)
);

INSERT INTO album(id_album, nom) VALUES
('1', 'album1'),
('2', 'album2'),
('3', 'album3')
;

INSERT INTO sous_album(id_sous_album, nom, id_album) VALUES
('1', 'sous album 1', '1'),
('2', 'sous album 2', '1'),
('3', 'sous album 3', '1'),
('4', 'sous album 4', '2'),
('5', 'sous album 5', '2'),
('6', 'sous album 6', '3')
;

INSERT INTO photo(id_photo, nom, id_sous_album) VALUES
('1', 'photo1', '1'),
('2', 'photo2', '1'),
('3', 'photo3', '1'),
('4', 'photo4', '1'),
('5', 'photo5', '2'),
('6', 'photo6', '2'),
('7', 'photo7', '3'),
('8', 'photo8', '3'),
('9', 'photo9', '3'),
('10', 'photo10', '4'),
('11', 'photo11', '5'),
('12', 'photo12', '6'),
('13', 'photo13', '6'),
('14', 'photo14', '6'),
('15', 'photo15', '6')
;

SELECT distinct  album.nom, count(photo.id_photo)
from album, photo, sous_album
where album.id_album=sous_album.id_album
AND sous_album.id_sous_album=photo.id_sous_album
group by album.nom
order by album.nom`

这个查询给了我相册的名称和照片的数量,但我也想要sous专辑和他们的照片数量......你可以帮助我吗?

结果:

nom    | count(photo.id_photo)
album1 | 9
album2 | 2
album3 | 4

我需要这个结果:

nom          | count(photo.id_photo)
album1       | 9
sous album 1 | 4
sous album 2 | 2
sous album 3 | 3
album2       | 2
sous album 4 | 1
sous album 5 | 1
album3       | 4
sous album 6 | 4

2 个答案:

答案 0 :(得分:0)

SELECT x.*
     , y.*
  FROM 
     ( SELECT a.nom 
            , COUNT(*) total 
         FROM album a 
         JOIN sous_album ap 
           ON ap.id_album = a.id_album 
         JOIN photo p 
           ON p.id_sous_album = ap.id_sous_album
        GROUP 
           BY a.nom
     ) x
  JOIN  
     ( SELECT a.nom nom_album
            , ap.nom nom_sous_ablum
            , COUNT(*) total 
         FROM album a 
         JOIN sous_album ap 
           ON ap.id_album = a.id_album 
         JOIN photo p 
           ON p.id_sous_album = ap.id_sous_album 
        GROUP 
           BY a.nom
            , ap.nom
     ) y
    ON y.nom_album = x.nom;

请注意,如果至少有一个与之关联的sous_album(和照片),此特定查询将仅返回相册。

答案 1 :(得分:0)

感谢您的解决方案......我找到了另一个......

SELECT a.nom, sa.nom, COUNT( * ) AS NbPhoto FROM album a INNER JOIN sous_album sa ON sa.id_album = a.id_album INNER JOIN photo p ON p.id_sous_album = sa.id_sous_album GROUP BY a.nom, sa.nom WITH ROLLUP