使用mysql获取最早的datetime值

时间:2013-12-29 15:37:15

标签: php mysql

我有这个mySQL-table

CREATE TABLE `products_to_categories` (
  `products_id` int(11) NOT NULL,
  `categories_id` int(11) NOT NULL,
  `date_added` datetime NOT NULL,
  PRIMARY KEY (`products_id`,`categories_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

products_id 2085有三个条目,因为它分为三类。

products_id    categories_id    date_added
2085           204              2013-03-01
2085           143              2013-03-13
2085           86               2013-03-25

实际上我有这个查询按date_added

订购它们
SELECT   categories_id,
         products_id
FROM     products_to_categories
WHERE    categories_id != 0
ORDER BY date_added

如何使用查询获取最旧的值(在本例中为2013-03-01)?

5 个答案:

答案 0 :(得分:3)

使用聚合函数MIN

SELECT MIN(date_added) AS OldestDate
FROM products_to_categories
WHERE products_id = 2085;

如果您要查找每种产品的最早日期,请添加GROUP BY

SELECT products_id, MIN(date_added) AS OldestDate
FROM products_to_categories
GROUP BY products_id;

答案 1 :(得分:1)

以下是获取整行的方法:

select ptc.*
from products_to_categories ptc
where products_id = 2085 
order by date_added
limit 1;

这将使用products_to_categories(products_id, date_added)上的索引进行优化。

编辑:

每种产品的最旧值:

select products_id, min(date_added)
from products_to_categories ptc
group by products_id;

答案 2 :(得分:0)

通过这种方式,您可以获得每种产品最旧的一行。

SELECT products_id, categories_id, MIN(date_added)
FROM products_to_categories
WHERE categories_id != 0
GROUP BY products_id

答案 3 :(得分:0)

SELECT date_added AS OldestDate
FROM products_to_categories
order by OldestDate
limit 1;

演示:http://www.sqlfiddle.com/#!2/eb462/2

答案 4 :(得分:0)

如果您的条目是基于日期的,那么您可以使用Min运算符

SELECT products_id,MIN(date_added) AS OldDate
FROM products_to_categories group by products_id

以上查询将选择所有products_id的日期最小值。