gpt4 book ai didi

mysql - 在 mysql 中使用内部连接和别名

转载 作者:行者123 更新时间:2023-12-01 00:41:55 26 4
gpt4 key购买 nike

我正在尝试连接同一张表中的多个不同值。我试图从不同的时间范围返回查询中的打印率(月/日/年/周等打印了多少),当我执行下面的查询时出现 1064 错误。怎么解释?

SELECT t1.station_name, t1.yearpages, t2.monthpages
FROM (
SELECT station_name, SUM(print_pages) yearpages
FROM `file_prints`
WHERE year(print_date) = 2014;
) t1
INNER JOIN (
SELECT station_name, sum(print_pages) monthpages
FROM `file_prints`
WHERE month(print_date) = 2;
) ON t1.station_name = t2.station_name;

那么,如果我要添加多个连接,查询会像这样吗?

SELECT t1.station_name, t1.station_name as db_name, t1.yearpages, t2.monthpages, t3.daypages, t4.weekpages
FROM (
SELECT station_name, sum(print_pages) yearpages
FROM `file_prints`
WHERE year(print_date) = $year;
GROUP BY station_name
) t1
INNER JOIN (
SELECT station_name, sum(print_pages) monthpages
FROM `file_prints`
WHERE month(print_date) = $month;
GROUP BY station_name
) t2 ON t1.station_name = t2.station_name
INNER JOIN (
SELECT station_name, sum(print_pages) daypages
FROM `file_prints`
WHERE dayofmonth(print_date) = $day;
GROUP BY station_name
) t3 ON t2.station_name = t3.station_name
INNER JOIN (
SELECT station_name, sum(print_pages) weekpages
FROM `file_prints`
WHERE week(print_date) = $week;
GROUP BY station_name
) t4 ON t3.station_name = t4.station_name

最佳答案

仅使用条件聚合怎么样?

SELECT station_name,
sum(case when year(print_date) = $year then print_pages end) as yearpages,
sum(case when month(print_date) = $month then print_pages end) as monthpages,
sum(case when day(print_date) = $day then print_pages end) as daypages,
sum(case when week(print_date) = $week then print_pages end) as weekpages
FROM `file_prints`
GROUP BY station_name;

关于mysql - 在 mysql 中使用内部连接和别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30114338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com