【问题标题】:Join two Mysql tables by unique keywords and by adding total in column通过唯一关键字和在列中添加总计来连接两个 Mysql 表
【发布时间】:2013-05-21 11:20:06
【问题描述】:

我正在尝试将每个位置的每日总数放到另一个表中。

结构如下:

reports_location_temp:

Table_Name:           Date:                              Total_Count:
London                2013-05-26 10:49:53                5000
London                2013-05-26 10:49:53                2000
Birmingham            2013-05-26 10:49:53                1000
London                2013-05-26 10:49:53                5000
Manchester            2013-05-26 10:49:53                50
Birmingham            2013-05-26 10:49:53                500

reports_location_total_daily:

Table_Name:           Date:                              Total_Count:
London                2013-05-26 23:55:00                12000
Manchester            2013-05-26 23:55:00                50
Birmingham            2013-05-26 23:55:00                1500

我仍在学习 Mysql。

这是我尝试过的查询,但它只为每个 Unique Table_Name 选择一列:

UPDATE reports_Location_total_daily j1 INNER JOIN reports_location_temp l1 ON j1.Table_Name = l1.Table_Name SET j1.Total_Count = l1.Total_Count    

感谢您对此的帮助。

【问题讨论】:

  • 为什么不写2个请求:从第一个中选择,按Table_Name分组并更新第二个表?
  • 调查命令insert into . . . on duplicate key

标签: mysql sql inner-join outer-join


【解决方案1】:
CREATE TABLE sales
(id INT NOT NULL AUTO_INCREMENT,
location VARCHAR(40), 
today DATETIME NOT NULL,
sales INT NOT NULL,
PRIMARY KEY (id)
)
;


INSERT sales (location,today,sales) VALUES ('London','2013-05-26',2000);
INSERT sales (location,today,sales) VALUES ('Birm','2013-05-26',1000);
INSERT sales (location,today,sales) VALUES ('London','2013-05-26',1500);
INSERT sales (location,today,sales) VALUES ('London','2013-05-24',100);
INSERT sales (location,today,sales) VALUES ('Birm','2013-05-24',200);
INSERT sales (location,today,sales) VALUES ('London','2013-05-24',300);

CREATE TABLE daily_totals
(id INT NOT NULL AUTO_INCREMENT,
location VARCHAR(40), 
today DATETIME NOT NULL,
totalsales INT NOT NULL,
PRIMARY KEY (id)
)
;

DELETE FROM daily_totals;

INSERT INTO daily_totals (location,today,totalsales)
SELECT location,
DATE(today),
SUM(sales)
FROM sales
GROUP BY location,DATE(today)

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 2012-12-09
    • 2011-02-17
    • 2013-01-07
    • 2022-11-19
    • 1970-01-01
    相关资源
    最近更新 更多