Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 与最多两列比较,得到一行_Mysql_Sql - Fatal编程技术网

Mysql 与最多两列比较,得到一行

Mysql 与最多两列比较,得到一行,mysql,sql,Mysql,Sql,我有一个表test,列为id、month、year。我需要在一个查询中获取id,其中最长为月份,最长为年份 比如说 id month year 1 10 2012 2 9 2013 我的结果应该是id 2 首先根据最长月份检查年份,然后根据这些检查我需要获得id 我在MySQL中给出这样的查询 select id from book where MAX(month) and MAX(year); 其生产错误您可以使用DESC关键字按年

我有一个表test,列为id、month、year。我需要在一个查询中获取id,其中最长为月份,最长为年份

比如说

id     month   year
1       10     2012

2        9     2013
我的结果应该是id 2

首先根据最长月份检查年份,然后根据这些检查我需要获得id

我在MySQL中给出这样的查询

 select id from book where MAX(month) and MAX(year);

其生产错误

您可以使用DESC关键字按年、月订购:)


只需使用月份和年份进行排序:


对于这种类型的查询,
orderby
limit
是最好的方法。您似乎想要最新的日期,所以从年份(降序)开始,然后从月份(降序)开始:


特别是,您不需要最长月份和最长年份。根据您想要的结果,您需要最近/最近一个月的数据。

是的,但不要忘记-如果您需要获得最大值,您必须使用DESC;)进行排序您需要首先按年份排序:)您需要的最大月份是10,其中最大年份是2013年。那你需要什么?按年或按月。
SELECT id 
FROM book 
ORDER BY year DESC, month DESC 
LIMIT 0, 1
SELECT id
FROM   books
ORDER  BY year DESC, month DESC
LIMIT  1
select *
from book
order by year desc, month desc
limit 1