SQL查询返回错误的结果集

时间:2016-06-03 09:02:18

标签: mysql sql

我有这张桌子:

columns:
Id  product_id name status update_date

1   1   prod1   bought  2016-04-20 10:10:10
2   1   prod1   sold    2016-04-22 12:25:00
3   1   prod1   sold    2016-06-03 09:42:15

我想执行此查询:

select id,name,status,max(update_date) from product group by name,status;

我明白了:

1   prod1   bought  2016-04-20 10:10:10
2   prod1   sold    2016-06-03 09:42:15

对于结果集中的第二行,我必须得到:

3   prod1   sold    2016-06-03 09:42:15

而不是:2 prod1 sold 2016-06-03 09:42:15

4 个答案:

答案 0 :(得分:1)

试试这个;)

select id,name,status,update_date from product
where (name, status, update_date) in (
    select name,status,max(update_date) from product
    group by name,status
)

或者

select t1.id, t1.name, t1.status, t1.update_date
from product t1
inner join (
    select name,status,max(update_date) as update_date from product
    group by name,status
) t2 on t1.name = t2.name and t1.status = t2.status and t1.update_date = t2.update_date

答案 1 :(得分:1)

简单查询,试​​试这个

Pink

答案 2 :(得分:0)

select distinct A.id, A.name, A.status, A.update_date 
  from product A,
(select `name`,status,max(update_date) update_date
   from product
  group by `name`, status) B
where A.name=B.name and A.status=b.status and a.update_date=b.update_date

解释:如果您有2个确切的update_dates

,则使用distinct

SQLFiddle:http://www.sqlfiddle.com/#!9/b8218/2

答案 3 :(得分:0)

我已经尝试了查询,但它正在运行。

CREATE TABLE  ##product(
Id  INT,
product_id INT,
name NVARCHAR(100),
 status NVARCHAR(100),
 update_date DATETIME
 );

INSERT INTO ##product
 VALUES
 (1,   1,   'prod1',   'bought',  '2016-04-20 10:10:10'),
( 2,   1,   'prod1',   'sold',    '2016-04-22 12:25:00'),
 (3,   1,  'prod1' ,  'sold',    '2016-06-03 09:42:15')

 SELECT id, name, status, update_date FROM ##product WHERE update_date IN 
 (
 SELECT MAX(update_date) FROM ##product GROUP BY name, status
 )


 DROP TABLE ##product