简体   繁体   中英

Alter table add column as SELECT

So I wanted to add new column to my table made from a select using two other tables. 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; 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

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; 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. That needs to be done in a separate UPDATE statement.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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