在Mysql中,我們可以使用WEEKDAY函數來查詢某一天是星期幾。
SELECT WEEKDAY('2021-09-03');
該查詢的結果是:
+------------------------+ | WEEKDAY('2021-09-03') | +------------------------+ | 4 | +------------------------+
其中,0表示星期一,1表示星期二,以此類推。
如果我們想查詢某個月的所有日期是星期幾,可以使用如下查詢:
SELECT DATE_FORMAT(cal_date, '%Y-%m-%d') AS date, WEEKDAY(cal_date) AS weekday FROM ( SELECT ADDDATE('2021-09-01', t4 * 10000 + t3 * 1000 + t2 * 100 + t1 * 10 + t0) AS cal_date FROM (SELECT 0 t0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t0, (SELECT 0 t1 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t1, (SELECT 0 t2 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t2, (SELECT 0 t3 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t3, (SELECT 0 t4 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) t4 ) dates WHERE MONTH(cal_date) = 9;
該查詢會返回9月份的所有日期及其對應的星期幾。
我們可以將查詢結果使用PHP的循環來輸出:
$query = "SELECT DATE_FORMAT(cal_date, '%Y-%m-%d') AS date, WEEKDAY(cal_date) AS weekday FROM ( SELECT ADDDATE('2021-09-01', t4 * 10000 + t3 * 1000 + t2 * 100 + t1 * 10 + t0) AS cal_date FROM (SELECT 0 t0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t0, (SELECT 0 t1 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t1, (SELECT 0 t2 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t2, (SELECT 0 t3 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t3, (SELECT 0 t4 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) t4 ) dates WHERE MONTH(cal_date) = 9"; $result = mysqli_query($connection, $query); while ($row = mysqli_fetch_assoc($result)) { echo "日期:" . $row['date'] . " 星期:" . ($row['weekday'] + 1) . "
"; }
這樣就可以輸出所有日期及其對應的星期了。