简体   繁体   English

如何使数据库列成为另一列的 function

[英]How do I make a database column a function of another column

I'm trying to make a database column which would be the percent of the value in another column我正在尝试创建一个数据库列,该列将是另一列中值的百分比

<?php
$sql = "ALTER TABLE inventorylist
        ADD COLUMN percent DOUBLE 
        GENERATED ALWAYS AS (turnover/SUM(turnover)*100);"; 
?>

As already commented generated columns can only refer to the columns of the same row.如前所述,生成的列只能引用同一行的列。 But you could try a view including the calculation.但是您可以尝试包含计算的视图。 Something along the lines of:类似的东西:

CREATE VIEW inventorylist_with_percent
AS
SELECT il1.*,
       il1.turnover / (SELECT sum(il2.turnover)
                              FROM inventorylist il2) * 100 percent
       FROM inventorylist il1;

I think it will safe to say let your code logic handle that task instead of pushing it to the database.我认为可以安全地说让您的代码逻辑处理该任务而不是将其推送到数据库。 Write a code that does the computation while inserting or while querying from the database.编写一段代码,在插入或查询数据库时进行计算。

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

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