简单MySQL视图由不同表中的聚合数据组成

时间:2019-03-02 22:38:12

标签: mysql sql view

尝试制作一个简单的视图,将总计合为一行。这里的窍门是我想从多个表中获得这些总计。

通过这种方式,我可以只选择该行以获得一堆我想跟踪的东西的总和。

到目前为止,我无法解决这个问题,有关此类事情的大多数帖子都与联接有关。

//OrderContainer.vue

    <template>
        <my-vue-avatar v-if="hasID" class="img-avatar" :id="avatarPicId"></my-vue-avatar>
    ....
    </template>
    <script>
    import MyVueAvatar from '../Avatar'
    ....
    data(){
            return { 
                avatarPicId:'',
                hasID: false
            }
        },
    beforeMount(){
        this.$eventBus.$on('idChange',id => {
            //this fanction will get triggered every time an `idChange` event fires.
            //lets assign the new value to our `avatarPicId`:
            this.avatarPicId = id;
            this.hasID = !!this.avatarPicId; //assign a boolean to this.hasID, wether the accepted id isnt undefined,null,false or empty string.
            //this.avatarPicId is sent as props to `my-vue-avatar` child component.
            //it should re-evaluates itself. if its not happening, you can  
             //cause here a complete destruction of MyVueAvatar 
             //component:
              this.hasID = false;
              //and a re-rendering, after the destruction is completed:
              this.$nextTick(()=> this.hasID = true);
        })
    },
}
</script>

2 个答案:

答案 0 :(得分:1)

您可以在SELECT中使用子查询:

CREATE VIEW stats AS
  select (select COUNT(DISTINCT p.name) from publisher p) as totalPublisher,
         (select COUNT(DISTINCT s.name) from series s) as totalSeries;

注意:这些表中的名称很可能是不同的。如果是这样,这样做会更有效:

CREATE VIEW stats AS
  select (select count(*) from publisher p) as totalPublisher,
         (select count(*) from series s) as totalSeries;

答案 1 :(得分:1)

  

[…]简单视图,将总计合为一行[…]

不过,您所描述的并不简单;它涉及计算不同记录集的总数。也就是说,必然是一个复杂的查询,它将不同的记录集组合在一起。

您是正确的,联接是执行此操作的好方法(一个原因是,它告诉RDBMS您想要什么结果,而不是如何获得结果)。但是,在您给出的特定示例中,您试图将它们汇总成一行的值之间显然没有关联。

另一种实现方式:

CREATE VIEW stats AS
SELECT
    COUNT (SELECT DISTINCT name FROM publisher) AS total_publisher,
    COUNT (SELECT DISTINCT name FROM series) AS total_series