我想从每周存储日期时间字段的表中获取记录。 一个mysql查询,可以识别周数和周开始和结束日期。
如链接中所示。
https://www.epochconverter.com/weeks/2017
如何通过mysql查询获取该记录,包括周数,该周的开始和结束日期以及一周的开始和结束日期之间的记录。不适用于当前或单周。过去几周我需要它们来记录数据库表中可用的日期时间值。 即
Week (number to know?) - Start date - end date.
Week 01 - Start date - January 2, 2017 ---- End date -- January 8, 2017
|-> All records in it.
Week 02 - Start date - January 9, 2017 ---- End date -- January 15, 2017
|-> All records in it.
答案 0 :(得分:0)
让你的数据库中有main_table
一些数据。例如:
CREATE TABLE `main_table` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Date` date NOT NULL,
`Description` varchar(45) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT main_table
(`Date`, Description)
VALUES
('2017-01-02','The first record'),
('2017-01-05','The second record'),
('2017-01-11','The third record'),
('2017-01-17','The fourth record');
创建用户定义的函数,该函数返回与指定日期相同的特定日期的日期。使用CREATE FUNCTION语法:
DELIMITER $$
CREATE FUNCTION `GET_DAY_OF_WEEK` (`date` DATE, `day` TINYINT UNSIGNED)
RETURNS DATE
BEGIN
RETURN `date`- INTERVAL WEEKDAY(`date`) + 1 DAY + INTERVAL `day` DAY;
END$$
DELIMITER ;
如果你的星期是星期一开始,那么星期一使用1
,星期日使用7
。如果你的星期是星期日开始,那么星期日使用0
,星期六使用6
。例如,我的星期是星期一开始的,我希望上周三的日期,然后
SELECT GET_DAY_OF_WEEK('2017-06-03', 3);
返回'2017-05-31'
因此,要每周获取main_table
的记录,您可以使用以下MySQL查询:
SELECT
ID,
WEEKOFYEAR(`Date`) AS WeekNum,
GET_DAY_OF_WEEK(`Date`, 1) AS WeekStarted,
GET_DAY_OF_WEEK(`Date`, 7) AS WeekFinished,
Description
FROM main_table;
查询结果将是
ID WeekNum WeekStarted WeekFinished Description
1 1 2017-01-02 2017-01-08 'The first record'
2 1 2017-01-02 2017-01-08 'The second record'
3 2 2017-01-09 2017-01-15 'The third record'
4 3 2017-01-16 2017-01-22 'The fourth record'
答案 1 :(得分:-2)
了解如何获取周here,然后在日期之间获取mysql数据,请使用以下语句:
$sql = "SELECT * FROM stock WHERE dateColumnName BETWEEN '{$startDate}' AND '{$endDate}'";
确保日期格式为' Y-m-d'。
更新:
以下是适用于我的完整代码:
<?php
function getStartAndEndDate($week, $year) {
$dto = new DateTime();
$dto->setISODate($year, $week);
$ret['week_start'] = $dto->format('Y-m-d');
$dto->modify('+6 days');
$ret['week_end'] = $dto->format('Y-m-d');
return $ret;
} ?>
<table>
<tr>
<th>Week Number</th>
<th>From Date</th>
<th>To Date</th>
</tr>
<?php
for($i=1; $i<=52; $i++){
$week_array = getStartAndEndDate($i,2017);
$sql = "SELECT * FROM stock WHERE on_date BETWEEN '{$week_array['week_start']}' AND '{$week_array['week_end']}'";
$result = mysqli_query($con,$sql);
$item = mysqli_fetch_assoc($result);
echo "<tr>
<td>Week $i </td>
<td>".$week_array['week_start']."</td>
<td>".$week_array['week_end']."</td>
<td>".$item['id']."</td>
</tr>";
} ?>
</table>