我需要基于SQL中的COUNT函数从表中SELECT记录

时间:2013-10-21 01:46:08

标签: sql select count

我有四张桌子:

  PAINTING            GALLERY             ARTIST              PAINTED
- PAINTING_TITLE    - GALLERY_ID        - ARTIST_ID         - PAINTED_CODE
- PAINTING_ID       - GALLERY_NAME      - ARTIST_LAST       - ARTIST_ID
                                        - ARTIST_FIRST      - PAINTING_ID

PAINTED表跟踪每位艺术家绘制的绘画。有些画作是由不止一位艺术家绘制的。 我想回复两位艺术家画的画作清单。

SELECT PAINTING.PAINTING_TITLE AS TITLE, 
   GALLERY.GALLERY_NAME AS GALLERY, 
   ARTIST.ARTIST_FIRST AS ARTISTFIRST, 
   ARTIST.ARTIST_LAST AS ARTISTLAST
FROM PAINTING, GALLERY, PAINTED, ARTIST
WHERE PAINTING.GALLERY_ID = GALLERY.GALLERY_ID
AND PAINTING.PAINTING_ID = PAINTED.PAINTING_ID
AND ARTIST.ARTIST_ID = PAINTED.ARTIST_ID
AND (SELECT COUNT(*) FROM PAINTED, PAINTING, ARTIST
WHERE PAINTING.GALLERY_ID = GALLERY.GALLERY_ID
AND PAINTING.PAINTING_ID = PAINTED.PAINTING_ID
AND ARTIST.ARTIST_ID = PAINTED.ARTIST_ID) = 2;

这不会返回我需要的结果。你对如何只选择有两位艺术家的画作有什么想法吗?

我正在使用Access SQL,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

使用GROUP BY代替内部SELECT

SELECT
    PAINTING.PAINTING_TITLE AS TITLE, 
    GALLERY.GALLERY_NAME AS GALLERY
FROM
    PAINTING,
    GALLERY,
    PAINTED
WHERE
        PAINTING.GALLERY_ID = GALLERY.GALLERY_ID
    AND
        PAINTING.PAINTING_ID = PAINTED.PAINTING_ID
GROUP BY
    PAINTING.PAINTING_TITLE,
    GALLERY.GALLERY_NAME
HAVING
    COUNT(PAINTED.ARTIST_ID) = 2