2011-01-07 118 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和某些运算符来提取非唯一(最大和小于今天)记录!