简体   繁体   English

如何从MySQL中的FROM字段中删除子查询

[英]How to remove a subquery from the FROM field in MySQL

I'm new to MySQL and databases and I've seen in many places that it is not considered a good programming practice to use subqueries in the FROM field of SELECT in MySQL, like this: 我是MySQL和数据库的新手,我在许多地方都看到,在MySQL的SELECT字段中使用子查询并不是一个好的编程习惯,如下所示:

select userid, avg(num_pages) 
from (select userid , pageid , regid , count(regid) as num_pages 
      from reg_pag 
      where ativa = 1 
      group by userid, pageid) as from_query 
group by userid;

which calculates the average number of registers per page that the users have. 它计算用户每页的平均寄存器数。

The reg_page table looks like this: reg_page表如下所示: reg_page表图像

Questions: 问题:

  1. How to change the query so that it doesn't use the subquery in the FROM field? 如何更改查询,以便它不使用FROM字段中的子查询?

  2. And is there a general way to "flatten" queries like this? 是否有一种通常的方式来“扁平化”这样的查询?

One way is to use count(distinct) : 一种方法是使用count(distinct)

select userid, count(*) / count(distinct pageid)
from reg_pag 
where ativa = 1
group by userid;

The average number of registers per page per user can also be calculated as number of registers per user divided by number of pages per user. 每个用户每页的平均寄存器数也可以计算为每个用户的寄存器数除以每个用户的页数。 Use count distinct to count only distinct psgeids per user: 使用count distinct来计算每个用户只有不同的psgeids:

select userid, count(regid) / count(distinct pageid) as avg_regs
from reg_pag 
where ativa=1
group by userid;

There is no general way of flattening such queries. 没有通用的方法来展平这些查询。 It may not even be possible to flatten some of them, otherwise there would be little point in having this feature in the first place. 它甚至可能不会使其中的一些变平,否则首先要有这个功能是没有意义的。 Do not get scared of using subqueries in the from clause, in some occasions they may be even more effective, than a flattened query. 不要害怕在from子句中使用子查询,在某些情况下,它们可能比扁平查询更有效。 But this is vendor and even version specific. 但这是供应商甚至特定版本。

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

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