Select 所有具有特定日期且仅被记录一次的用户
Select all user that have a specific date and have been recorded only one time
我有这个table。
ID Date Value
___ ____ _____
3241 01/01/00 15456
3241 9/17/12 5
3241 9/16/12 100
3241 9/15/12 20
4355 01/01/00 01
4355 9/16/12 12
4355 9/15/12 132
4355 9/14/12 4
1001 01/01/00 456
1001 9/16/12 125
5555 01/01/00 01
1234 01/01/00 01
1234 9/16/12 45
2236 01/01/00 879
2236 9/15/12 128
2236 9/14/12 323
2002 01/01/00 567
我想select
所有具有01-01-00 as date
且只显示过一次的记录。
我想要的结果就像下面的 table。
ID Date Value
___ ____ _____
5555 01/01/00 01
2002 01/01/00 567
我尝试使用 HAVING
子句,但由于 GROUP BY
,结果是 错误的 因为我的一位 select 有不止一条记录,这对我的情况不利。
我的错误尝试:
SELECT * FROM
(SELECT *
FROM table1
GROUP BY id, date, value
HAVING count(Id)=1) t1
WHERE date='01-01-00'
使用IN
SELECT *
FROM table1
WHERE id IN (
SELECT id
FROM table1
GROUP BY id
HAVING count(Id)=1
) and date='01-01-00'
将您的查询更改为
SELECT *
FROM
(SELECT *
FROM table1
GROUP BY id
HAVING count(id)=1) t1
WHERE t1.date='01-01-00'
我会使用:
select id, max(date) as date, max(value) as value
from t1
group by id
having max(date) = '01-01-00' and count(*) = 1;
一种更快的方法可能是:
select t1.*
from t1
where date = '01-01-00' and
not exists (select 1 from t1 tt1 where tt1.id = t1.id and tt1.date <> '01-01-00');
这可以利用 t1(date)
和 t1(id, date)
上的索引。
我只是没有注意到我在我的 group by
中犯了一个错误,而不是只制作 ID
,我把所有的 columns
SELECT * FROM
(SELECT *
FROM Table1
GROUP BY `ID`
HAVING count(`ID`)=1) t1
WHERE `Date`='2000-01-01 00:00:00'
但是对于我的问题,我选择 因为它对我来说似乎更好。
PS:我有200万条记录
我有这个table。
ID Date Value
___ ____ _____
3241 01/01/00 15456
3241 9/17/12 5
3241 9/16/12 100
3241 9/15/12 20
4355 01/01/00 01
4355 9/16/12 12
4355 9/15/12 132
4355 9/14/12 4
1001 01/01/00 456
1001 9/16/12 125
5555 01/01/00 01
1234 01/01/00 01
1234 9/16/12 45
2236 01/01/00 879
2236 9/15/12 128
2236 9/14/12 323
2002 01/01/00 567
我想select
所有具有01-01-00 as date
且只显示过一次的记录。
我想要的结果就像下面的 table。
ID Date Value
___ ____ _____
5555 01/01/00 01
2002 01/01/00 567
我尝试使用 HAVING
子句,但由于 GROUP BY
,结果是 错误的 因为我的一位 select 有不止一条记录,这对我的情况不利。
我的错误尝试:
SELECT * FROM
(SELECT *
FROM table1
GROUP BY id, date, value
HAVING count(Id)=1) t1
WHERE date='01-01-00'
使用IN
SELECT *
FROM table1
WHERE id IN (
SELECT id
FROM table1
GROUP BY id
HAVING count(Id)=1
) and date='01-01-00'
将您的查询更改为
SELECT *
FROM
(SELECT *
FROM table1
GROUP BY id
HAVING count(id)=1) t1
WHERE t1.date='01-01-00'
我会使用:
select id, max(date) as date, max(value) as value
from t1
group by id
having max(date) = '01-01-00' and count(*) = 1;
一种更快的方法可能是:
select t1.*
from t1
where date = '01-01-00' and
not exists (select 1 from t1 tt1 where tt1.id = t1.id and tt1.date <> '01-01-00');
这可以利用 t1(date)
和 t1(id, date)
上的索引。
我只是没有注意到我在我的 group by
中犯了一个错误,而不是只制作 ID
,我把所有的 columns
SELECT * FROM
(SELECT *
FROM Table1
GROUP BY `ID`
HAVING count(`ID`)=1) t1
WHERE `Date`='2000-01-01 00:00:00'
但是对于我的问题,我选择
PS:我有200万条记录