如何为mysql选择具有某些条件的唯一值?

时间:2014-07-22 12:49:12

标签: mysql sql database

这里的表格如下:

CREATE TABLE my_table(id INT,user_id VARCHAR(5),add_date date);

INSERT INTO my_table
VALUES
  (1, 100, '2014-07-22'),
  (2, 400, '2014-07-22'),
  (3, 500, '2014-07-22'),
  (4, 500, '2014-07-22'),
  (5, 200, '2014-07-21'),
  (6, 300, '2014-07-21'),
  (7, 100, '2014-07-20'),
  (8, 200, '2014-07-20');

最初我需要检查2014-07-21到2014-07-22之间的查询日期和user_id分组,我有

**user_id** |  **add_date** 
        100 | 2014-07-22 
        400 | 2014-07-22
        500 | 2014-07-22
        200 | 2014-07-21
        300 | 2014-07-21

然后更多,我需要检查此表的完整数据。这个用户ID是否唯一?除日期条件外。

**Require Answer:**
 **user_id** |  **add_date**
         400 | 2014-07-22
         500 | 2014-07-22
         300 | 2014-07-21

注意:

我需要单一查询。

4 个答案:

答案 0 :(得分:1)

SELECT
   user_id, 
   max(add_date) 
FROM my_table
GROUP BY user_id
HAVING -- no date outside of the requested range
   MIN(add_date) BETWEEN '2014-07-21' and '2014-07-22'
AND 
   MAX(add_date) BETWEEN '2014-07-21' and '2014-07-22' 

答案 1 :(得分:0)

select 
   count(user_id) as c 
from 
   my_table 
having 
   c = 1 
   and add_date between '2014-07-21' 
   and '2014-07-22' 
group by 
   user_id

答案 2 :(得分:0)

使用LEFT OUTER JOIN为匹配的用户ID加入表格,但日期不匹配。按用户ID和日期分组,并使用必须检查没有匹配的用户: -

SELECT a.user_id, a.add_date
FROM my_table a
LEFT OUTER JOIN my_table b
ON a.user_id = b.user_id
AND a.add_date != b.add_date
WHERE a.add_date between '2014-07-21' and '2014-07-22'
GROUP BY a.user_id, a.add_date
HAVING COUNT(b.user_id) = 0

如果您只对日期范围内的重复项感兴趣,那么也要检查ON子句中表的第二个副本的日期范围

SELECT a.user_id, a.add_date
FROM my_table a
LEFT OUTER JOIN my_table b
ON a.user_id = b.user_id
AND a.add_date != b.add_date
AND b.add_date between '2014-07-21' and '2014-07-22'
WHERE a.add_date between '2014-07-21' and '2014-07-22'
GROUP BY a.user_id, a.add_date
HAVING COUNT(b.user_id) = 0

答案 3 :(得分:0)

您的条件实际上有点难以理解。我认为以下是您想要的:

select user_id, max(add_date)
from my_table
group by user_id
having max(add_date) between '2014-07-21' and '2014-07-22' and
       count(*) = 1;

目前尚不清楚这是什么意思:“除日期条件外。”