MySQL 如何在数据库查询中使用 MySQL 存储函数?
可以通过以下示例来理解,我们创建了一个名为“Profit”的函数来计算利润,并在数据库查询中将该函数应用于表“item_list”中的数据。
阅读更多:MySQL 教程
示例
mysql> CREATE FUNCTION profit(Cost DECIMAL (10,2),Price DECIMAL(10,2))
-> RETURNS DECIMAL(10,2)
-> BEGIN
-> DECLARE profit DECIMAL(10,2);
-> SET profit = price - cost;
-> RETURN profit;
-> END //
Query OK, 0 rows affected (0.07 sec)
mysql> Select * from item_list;
+-----------+-------+-------+
| Item_name | Price | Cost |
+-----------+-------+-------+
| Notebook | 24.50 | 20.50 |
| Pencilbox | 78.50 | 75.70 |
| Pen | 26.80 | 19.70 |
+-----------+-------+-------+
3 rows in set (0.00 sec)
上述查询显示了来自表 item_list 的数据。现在,在数据库查询中使用上面创建的 profit 函数,如下所示 –
mysql> Select *, profit(cost, price) AS Profit from item_list;
+-----------+-------+-------+--------+
| Item_name | Price | Cost | Profit |
+-----------+-------+-------+--------+
| Notebook | 24.50 | 20.50 | 4.00 |
| Pencilbox | 78.50 | 75.70 | 2.80 |
| Pen | 26.80 | 19.70 | 7.10 |
+-----------+-------+-------+--------+
3 rows in set (0.00 sec)
极客教程