简体   繁体   English

MySQL | 在特定日期使用列选择数据的最简单方法

[英]MySQL | Easiest way to select data with a column on a certain day

I have a table with the following structure 我有一个具有以下结构的表

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(32) | NO   |     | NULL    |                |
| time  | int(19)     | NO   |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

time being set to a UNIX_TIMESTAMP . time被设定为一个UNIX_TIMESTAMP

If I wanted to count the amount of values with a certain name, with a time value inside a day, would it be wise to change my table & application to use DATETIME type, or is there an easy way I could select different values for the day, and do this for multiple days & names. 如果我想用一天中的时间值来计算具有特定名称的值的数量,将表和应用程序更改为使用DATETIME类型是明智的选择,还是有一种简单的方法可以为表选择不同的值一天,并进行数天和多次命名。

I am using the PDO extension of PHP to query the database, and I am currently using the following code to create the query. 我正在使用PHPPDO扩展来查询数据库,并且当前正在使用以下代码来创建查询。

$stmt = $dbh->prepare("SELECT 
  (SELECT COUNT(*) FROM `test` WHERE `name`='name' AND `time` > :time1First AND `time` < :time1Second) AS `time1`, ...");

I will be happy to try and clarify anything that is not understood from this post. 我将很乐于尝试澄清本文中未理解的所有内容。 It seemed clear to me, but that is probably just because I was the one who wrote it. 对我来说似乎很清楚,但这可能只是因为我是撰写它的那个人。

In my honest opinion, I would use a datetime column data type. 坦白地说,我将使用datetime列数据类型。 They are easier to treat specially when doing queries like yours. 在执行像您这样的查询时,它们更易于特别处理。

BTW, your query seems correct, but you'll need to enter an int representing the UNIX_TIMESTAMP. 顺便说一句,您的查询似乎正确,但是您需要输入一个表示UNIX_TIMESTAMP的整数。

Regards, Xavi. 问候,哈维。

With GROUP BY you can count all times for every name. 使用GROUP BY,您可以计算每个名称的所有时间。 Try this 尝试这个

SELECT name, COUNT(*) as time1
  FROM test
 WHERE name = 'name' 
   AND time BETWEEN :time1First AND  :time1Second
 GROUP BY name
 ORDER BY name;

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

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