简体   繁体   中英

How do I subtract all prices in a mySQL table with SQL only?

I was playing with the following, but it's not there just yet.

ALTER TABLE `product_price` CHANGE `price` = `price` - 20;

What you're looking for is this:

UPDATE product_price SET price = price - 20;

So if your data looks like this:

| id | price         |
|----|---------------|
| 1  | 25.20         |
| 2  | 26.50         |
| 3  | 27.00         |
| 4  | 24.25         |

It will turn it to this:

| id | price         |
|----|---------------|
| 1  | 5.20          |
| 2  | 6.50          |
| 3  | 7.00          |
| 4  | 4.25          |

As tehvan pointed out in your comments, ALTER is used when you want to change the structure of the table. From the docs:

ALTER TABLE enables you to change the structure of an existing table. For example, you can add or delete columns, create or destroy indexes, change the type of existing columns, or rename columns or the table itself. You can also change the comment for the table and type of the table.

If you want to update information in any way you want to use the UPDATE statement.

As Paolo Bergantino mentioned, you tried to alter the structure of the table rather than the data contained in it. The SQL is made up of different parts, each responsible for something different. For defining your data structures (tables, views, etc.) you use the DDL (Data Definition Language). For manipulating data on the other hand, you use the DML (Data Manipulation Language).

This site shows the different parts of the SQL along with examples.

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