2012-04-03 51 views
3

中使用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 | 
+---------+-----------------+----------+-----------+--------+ 

我該如何調整我的查詢來做到這一點(跳過第一個匹配的結果)?

+0

定義 「第一個匹配的結果。」 SQL以集合的形式工作,並且沒有對集合進行排序的概念。你想跳過ArtId值最低的匹配結果嗎? – 2012-04-03 00:46:06

+2

爲什麼不是'ArtId = 9'跳過了? – 2012-04-03 00:47:05

+0

@AdamMihalcin,我明白這一點。我基本上希望其中一個副本被遺漏/跳過。我並不在乎哪一個,所以我認爲跳過第一個副本並選擇其餘部分可能是有意義的。 – 2012-04-03 00:55:07

回答

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 
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 
    ) 
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 
) 
+0

對不起,只是意識到它是在sqllite中,而不是sql服務器。我不確定您是否可以在sqllite的where子句中執行子查詢 – Greg 2012-04-03 00:59:50

相關問題