【问题标题】:Inserting into a temp table multiple counts for same row将同一行的多个计数插入临时表
【发布时间】:2016-02-15 13:28:35
【问题描述】:

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

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

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 语句失败了如何将选定的计数添加到临时表的单行中?

【问题讨论】:

  • 这是mysql 还是sql-server?它们不是一回事。
  • mysql 对不起,我没有看到我标记了那个。
  • 你的错误信息是什么?
  • 好吧,在我的测试中,它的第二次失败了。它与那个查询有关。这是 mysql 错误:#1054 - 'field list' 中的未知列 'countWeekly'
  • 没关系,我没有使用正确的列名。现在虽然它给了我 8 个结果?它应该只给我一个正确的结果集?

标签: php mysql


【解决方案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,一般来说。

【讨论】:

  • 其实这是一种我没想到的方式可能对我更有效。
【解决方案2】:

将你的第二个 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()))
)

【讨论】:

  • 哇...我不敢相信我漏掉了 values 关键字。这很有效,我犯了一个愚蠢的错误。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
  • 2019-07-26
  • 2019-06-07
  • 2018-02-06
  • 1970-01-01
相关资源
最近更新 更多