简体   繁体   English

为什么此查询不起作用?

[英]Why doesn't this query work?

I have this query: 我有这个查询:

select count(id) AS num,date_id from table
  where FROM_UNIXTIME(date_id,'%d-%m-%Y')='17-08-2009' order by date_id DESC;

This should result in all the id's posted on today's date, but it is giving only one id (the highest one). 这应该导致所有ID都发布在今天的日期上,但是它只给出一个ID(最高ID)。 When I remove count(id) from this query, it runs fine. 当我从该查询中删除count(id) ,它运行良好。

Why doesn't this count work with this query? 为什么此计数不适用于此查询?

Count is often paired with GROUP BY. 计数通常与GROUP BY配对。 Did you try GROUP BY date_id ? 您是否尝试了GROUP BY date_id

If you want to select total count for the date along with each date_id : 如果要选择日期的总计数以及每个date_id

SELECT  date_id, num
FROM    (
        SELECT  COUNT(id) AS num
        FROM    table
        WHERE   date_id >= UNIX_TIMESTAMP('17-08-2009')
                AND date_id < UNIX_TIMESTAMP('18-08-2009')
        )
CROSS JOIN
        table
WHERE   date_id >= UNIX_TIMESTAMP('17-08-2009')
        AND date_id < UNIX_TIMESTAMP('18-08-2009')
ORDER BY
        date_id DESC

When you have an aggregate function like COUNT in your query any columns that are not aggregated have to be mentioned in a group by clause. 当查询中具有COUNT等汇总函数时,必须在group by子句中提及所有未汇总的列。 The reason for this is that as your query stands it doesn't quite make sense with SQL's execution semantics. 这样做的原因是,如您的查询所示,它与SQL的执行语义完全没有关系。

This should work for you: 这应该为您工作:

select count(id) AS num,date_id
from table
where FROM_UNIXTIME(date_id,'%d-%m-%Y')='17-08-2009'
group by date_id
order by date_id DESC;

Also, since you're just getting from one date, you don't need the order by clause (since the query will only return one row anyways. 另外,由于您只是从一个日期开始,所以不需要order by子句(因为查询无论如何只会返回一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM