将临时表插入同一行的多个计数

时间:2015-11-13 20:59:53

标签: php mysql

我正在尝试创建一个临时表,并为表格显示:每年的结果数量每周计数|每天都计算在同一行。

所以第一行应该是这样的。

8 | 3 | 0所以这是针对在年,周,日中添加的所有记录

这是我的PHP代码来实现这一点,但它不允许我选择计数并将它们插入表中。

// Create temporary table
$sql = "CREATE TEMPORARY TABLE temp_overview(
company varchar(50),
countYearly int,
countWeekly int,
countDaily int    
)";

$stmt = $conn->prepare($sql);
if(!$stmt->execute()){
    echo "Failed first";    
}

// Insert into temp table
$sql = "INSERT INTO temp_overview(countYearly, countWeekly, countDaily)
SELECT
    (SELECT count(*) FROM client_companies WHERE YEAR(date_added) = YEAR(CURDATE())) AS companyCountY,
    (SELECT count(*) FROM client_companies WHERE DATE(date_added) >= DATE(DATE_SUB(NOW(), INTERVAL 7 DAY))) AS companyCountW,
    (SELECT count(*) FROM client_companies WHERE DAY(date_added) = DAY(CURDATE())) AS companyCountD
FROM
    client_companies";

$stmt = $conn->prepare($sql);
if(!$stmt->execute()){
    echo "Failed second";   
}

在第二个sql语句中失败了如何将所选计数添加到临时表中的单个行?

2 个答案:

答案 0 :(得分:1)

将您的第二个SQL修改为:

$sql = "INSERT INTO temp_overview(countYearly, countWeekly, countDaily) VALUES (
(SELECT count(*) FROM client_companies WHERE YEAR(date_added) = YEAR(CURDATE())),
(SELECT count(*) FROM client_companies WHERE DATE(date_added) >= DATE(DATE_SUB(NOW(), INTERVAL 7 DAY))),
(SELECT count(*) FROM client_companies WHERE DAY(date_added) = DAY(CURDATE()))
)

答案 1 :(得分:1)

模式

create table thing9
(   id int auto_increment primary key,
    theDate date not null
);
truncate table thing9;
insert thing9(theDate) values ('2015-11-09'),('2015-11-05'),('2015-10-20'),('2015-10-19'),
('2015-08-20'),('2015-01-20'),('2014-12-20'),('2014-07-20');
-- 8 rows

查询

SELECT
    (select count(*) from thing9 where DATE_SUB(NOW(), INTERVAL 1 WEEK)<=theDate) as withinWeek,
    (select count(*) from thing9 where DATE_SUB(NOW(), INTERVAL 1 MONTH)<=theDate) as withinMonth,
    (select count(*) from thing9 where DATE_SUB(NOW(), INTERVAL 1 YEAR)<=theDate) as withinYear;

+------------+-------------+------------+
| withinWeek | withinMonth | withinYear |
+------------+-------------+------------+
|          1 |           4 |          7 |
+------------+-------------+------------+

请参阅Mysql Date and Time Functions

上的手册页

使用interval非常酷。

一般来说,请查看date_adddate_subdatediff