简体   繁体   English

更改表添加列为 SELECT

[英]Alter table add column as SELECT

So I wanted to add new column to my table made from a select using two other tables.因此,我想使用其他两个表将新列添加到由 select 制成的表中。 I tried a query like this:我尝试了这样的查询:

ALTER TABLE order ADD cost DECIMAL(5,2) AS (SELECT SUM(price*pieces) FROM book JOIN details ON id_book=book_id GROUP BY order_id);

And I get error:我得到错误:

ERROR 1064 (42000): You have an error in your SQL syntax;错误 1064 (42000):您的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select sum(price*pieces) from book join details on id_book=book_id group by order_id ' at line 1检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在第 1 行的 id_book=book_id group by order_id 的 book join details on 'select sum(price*pieces) 附近使用

My other tables look like this:我的其他表如下所示:

CREATE TABLE details (
id_d INT(10) NOT NULL AUTO_INCREMENT,
book_id INT(10) DEFAULT NULL,
order_id INT(10) DEFAULT NULL,
pieces INT(10) DEFAULT NULL
...
CREATE TABLE book (
id_book INT(10) NOT NULL AUTO_INCREMENT,
price DECIMAL(5,2) DEFAULT NULL,
...

This SELECT SUM(price*pieces) FROM book JOIN details ON id_book=book_id GROUP BY order_id;SELECT SUM(price*pieces) FROM book JOIN details ON id_book=book_id GROUP BY order_id; works but I really don't know how to add this as a new column:(有效,但我真的不知道如何将其添加为新列:(

You can't specify the data to fill the column in the ALTER TABLE statement.您不能指定数据来填充ALTER TABLE语句中的列。 That needs to be done in a separate UPDATE statement.这需要在单独的UPDATE语句中完成。

ALTER TABLE order ADD cost DECIMAL(5,2) DEFAULT 0;

UPDATE order AS o
JOIN (
    SELECT d.order_id, SUM(d.pieces, * b.price) AS cost
    FROM details AS d
    JOIN book AS b ON d.book_id = b.id_book
    GROUP BY d.order_id) AS d ON d.order_id = o.order_id
SET o.cost = d.cost

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM