MySQL: Computed Column

前端 未结 4 1055
再見小時候
再見小時候 2020-12-03 16:42

I\'m just started using SQL and ran into a problem.

In my database, I presently have two tables, Cinemas and Theatres. I\'m trying to create a column \"# of Theatre

相关标签:
4条回答
  • 2020-12-03 17:01

    MySql does support generated columns in 5.7

    0 讨论(0)
  • 2020-12-03 17:06

    In mysql you if you want an actual column you would

    • create it as any column
    • make sure it is consistent by creating a trigger on theatre table that will update the column ever time a row is added or deleted
    0 讨论(0)
  • 2020-12-03 17:09

    it is possible. but you should not do it.

    that is called denormalization - and is usually not a good idea at all.

    sometimes however, you might absolutely need to denormalize something for some odd reason (your example is nowhere near a good reason). in these cases, you need to add trigger code to automatically manage the values whenever anything changes in the system that would affect the results.

    0 讨论(0)
  • 2020-12-03 17:09

    A computed column normally means a value you can calculate per row. MySQL does not support that, but SQL Server does. For example, to store the sum of two columns permanently:

    create table Table1 (a int, b int, c as a+b persisted)
    

    However, you're looking to store an aggregate, that is, a value for a group of rows. MySQL and SQL Server don't support materialized views with an aggregate, but Oracle does:

    create table Table1 (a int, b int);
    
    create materialized view View1 as
    select  a
    ,       count(*) as Cnt
    from    Table1
    group by
        a;
    

    With MySQL however, the closest you can do is a cronjob that periodically populates a table:

    truncate table Table1Summary;
    insert Table1Summary (a, Cnt) select a, count(*) from Table1;
    

    You can query the table like a materialized view; it will be as fast, but not guaranteed to be up to date.

    0 讨论(0)
提交回复
热议问题