如何跳过子查询的匹配结果?

时间:2012-04-03 00:42:34

标签: sql sqlite

使用sqlite3,我有一个如下所示的表:

+---------+-----------------+----------+-----------+--------+
| ArtId   |    Location     | ArtistID |  Title    |  Size  |
+---------+-----------------+----------+-----------+--------+
|  3      |      China      |   400    |   birds   | small  |
|  4      |      Samoa      |   670    |   stars   | large  |
|  5      |      Chile      |   427    |   clouds  | medium |
|  6      |        US       |   427    |   clouds  | small  |
|  7      |      France     |   123    |   collage | small  |
|  8      |      Spain      |   123    |   collage | large  |
|  9      |     Belarus     |   123    |   collage | medium |
+---------+-----------------+----------+-----------+--------+

我有一个查询产生所有结果,其中唯一的结果是具有重复标题和艺术家的结果:

SELECT * 
FROM LiveArt c1, (SELECT Title, ArtistID FROM LiveArt GROUP BY Title, ArtistID) c2 
WHERE c1.Title = c2.Title AND c1.ArtistID = c2.ArtistID

生成下表:

+---------+-----------------+----------+-----------+--------+
| ArtId   |    Location     | ArtistID |  Title    |  Size  |
+---------+-----------------+----------+-----------+--------+
|  5      |      Chile      |   427    |   clouds  | medium |
|  6      |        US       |   427    |   clouds  | small  |
|  7      |      France     |   123    |   collage | small  |
|  8      |      Spain      |   123    |   collage | large  |
|  9      |     Belarus     |   123    |   collage | medium |
+---------+-----------------+----------+-----------+--------+

我要归还的是:

+---------+-----------------+----------+-----------+--------+
| ArtId   |    Location     | ArtistID |  Title    |  Size  |
+---------+-----------------+----------+-----------+--------+
|  6      |        US       |   427    |   clouds  | small  |
|  8      |      Spain      |   123    |   collage | large  |
|  9      |     Belarus     |   123    |   collage | medium |
+---------+-----------------+----------+-----------+--------+

如何调整我的查询来执行此操作(跳过第一个匹配的结果)?

3 个答案:

答案 0 :(得分:1)

select * from tabName A
where A.ArtId !=
(
    select min(ArtId)
    from tabName B
    group by Title
    having A.Title=B.Title
);

ArtId       Location    ArtistID    Title       Size
----------  ----------  ----------  ----------  ----------
6           US          427         clouds      small
8           Spain       123         collage     large
9           Belarus     123         collage     medium

答案 1 :(得分:0)

SELECT c1.* 
FROM LiveArt c1
WHERE EXISTS 
      ( SELECT *
        FROM LiveArt c2
        WHERE c1.ArtID < c2.ArtID 
          AND c1.Title = c2.Title 
          AND c1.ArtistID = c2.ArtistID
      )

答案 2 :(得分:0)

可能有一种更有效的方法,但这样的事情可能会为您解决问题:

SELECT *
FROM LiveArt c1, 
(
  SELECT Title, ArtistID 
  FROM LiveArt 
  GROUP BY Title, ArtistID
) c2
WHERE c1.Title = c2.Title AND c1.ArtistID = c2.ArtistID 
AND c1.ARTID NOT IN 
( 
  SELECT MIN(ArtID) 
  FROM LiveArt
  GROUP BY Title, ArtistID
)