2011-01-07 89 views
1

我試圖根據返回數據集中多個列上的條件匹配來縮小現有複雜查詢的結果。我將盡可能在這裏儘可能簡化數據。MySQL - 根據兩列的重複排除select中的行

假設下面的表結構代表了我現有的複雜的查詢已經選擇的數據(由date這裏訂購):我需要從基於以下標準的數據集選擇

+----+-----------+------+------------+ 
| id | remote_id | type | date  | 
+----+-----------+------+------------+ 
| 1 |   1 | A | 2011-01-01 | 
| 3 |   1 | A | 2011-01-07 | 
| 5 |   1 | B | 2011-01-07 | 
| 4 |   1 | A | 2011-05-01 | 
+----+-----------+------+------------+ 

  • 如果remote_idtype配對是唯一的一套,返回總是排
  • 如果配對和type獨特的一套,採取以下行動:
    • 套行對其中的remote_idtype配對不是唯一的,返回單行爲其date最大且仍然現在小於或等於

所以,如果今天是2011-01-10,我想在數據集中返回的是:

+----+-----------+------+------------+ 
| id | remote_id | type | date  | 
+----+-----------+------+------------+ 
| 3 |   1 | A | 2011-01-07 | 
| 5 |   1 | B | 2011-01-07 | 
+----+-----------+------+------------+ 

對我有沒有運氣包裹我的頭圍繞這一某種原因。我懷疑答案在於group by的良好應用,但我無法理解它。任何幫助是極大的讚賞!

+0

你說非獨特的行,你想返回最大的日期,但仍然<=現在。您爲A類拉的日期大於您爲「今日」指定的日期。 – 2011-01-07 18:54:54

+0

我的錯誤!我忘了是2011年;)更正了OP。 – 2011-01-07 18:59:02

回答

4
/* Rows with exactly one date - always return regardless of when date occurs */ 
SELECT id, remote_id, type, date 
    FROM YourTable 
    GROUP BY remote_id, type 
    HAVING COUNT(*) = 1 
UNION 
/* Rows with more than one date - Return Max date <= NOW */ 
SELECT yt.id, yt.remote_id, yt.type, yt.date 
    FROM YourTable yt 
     INNER JOIN (SELECT remote_id, type, max(date) as maxdate 
         FROM YourTable 
         WHERE date <= DATE(NOW()) 
         GROUP BY remote_id, type 
         HAVING COUNT(*) > 1) sq 
      ON yt.remote_id = sq.remote_id 
       AND yt.type = sq.type 
       AND yt.date = sq.maxdate 
1

group by子句將具有相同值的一列或多列的所有行組合在一起,並在結果集中爲它們返回一行。如果您使用將應用於每個「組」的聚合函數(最小值,最大值,總和,平均值等)。

SELECT id, remote_id, type, max(date) 
FROM blah 
GROUP BY remote_id, date; 

我不是妓女,其中今天的日期到來時,卻認爲是複雜的查詢,你沒有描述的一部分,我想是不是在這裏你的問題直接相關。

+0

分鐘太晚:( – suhprano 2011-01-07 18:53:09

+0

這不是競爭:) – 2011-01-07 18:56:40

0

試試這個

 
select id, remote_id, type, MAX(date) from table 
group by remote_id, type 
1

試試這個:

SELECT a.* 
    FROM table a INNER JOIN 
      (
       select remote_id, type, MAX(date) date, COUNT(1) cnt from table 
       group by remote_id, type 
      ) b 
WHERE a.remote_id = b.remote_id, 
       AND a.type = b.type 
       AND a.date = b.date 
       AND ((b.cnt = 1) OR (b.cnt>1 AND b.date <= DATE(NOW()))) 
0

嗨卡森!您可以嘗試在這兩個字段上使用「distinct」關鍵字,並且在聯合中,您可以使用Count()以及group by和某些運算符來提取非唯一(最大和小於今天)記錄!