简体   繁体   English

MySQL替代子查询/联接

[英]MySQL alternative to subquery/join

I am looking for an efficient alternative to subqueries/joins for this query. 我正在为此查询寻找一种有效的替代子查询/联接的方法。 Let's say I a table that stores information about companies with the following columns: 假设我有一个表,其中存储有关公司的信息,其中包含以下列:

  • name: the name of the company 名称:公司名称
  • state: the state the company is located in 州:公司所在的州
  • revenue: the annual revenue of the company 收入:公司的年收入
  • employees: how many employees this company has 员工:这家公司有多少员工
  • active_business: wether or not the company is in business (1 = yes, 0 = no) active_business:公司是否营业(1 =是,0 =否)

Let's say that from this table, I want to find out how many companies in each state meet the requirement for some minimum amount of revenue, and also how many companies meet the requirement for some minimum number of employees. 假设从此表中,我想找出每个州有多少公司满足最低收入要求,还有多少公司达到最低雇员人数要求。 This can be expressed as the following subquery (can also be written as aa join): 这可以表示为以下子查询(也可以写为aa join):

SELECT state,
       (
            SELECT count(*)
            FROM records AS a
            WHERE a.state = records.state
              AND a.revenue > 1000000
       ) AS companies_with_min_revenue,
       (
            SELECT count(*)
            FROM records AS a
            WHERE a.state = records.state
              AND a.employees > 10
       ) AS companies_with_min_employees
FROM records
WHERE active_business = 1
GROUP BY state

My question is this. 我的问题是这个。 Can I do this without the subqueries or joins? 我可以在没有子查询或联接的情况下执行此操作吗? Since the query is already iterating over each row (there's no indexes), is there some way I can add a condition that if the row meets the minimum revenue requirements and is in the same state, it will increment some sort of counter for the query (similar to map/reduce)? 由于查询已经在每行上进行了迭代(没有索引),因此我可以通过某种方式添加条件:如果该行满足最低收入要求并且处于相同状态,它将为查询增加某种计数器(类似于map / reduce)?

I think CASE and SUM will solve it: 我认为CASESUM将解决它:

SELECT state
    , SUM(CASE WHEN R.revenue > 1000000 THEN 1 ELSE 0 END) AS companies_with_min_revenue
    , SUM(CASE WHEN R.employees > 10 THEN 1 ELSE 0 END) AS companies_with_min_employees
    FROM records R
    WHERE R.active_business = 1
    GROUP BY R.state

As you can see, we will have a value of 1 per record with a revenue of greater than 1000000 (else 0), then we'll take the sum. 如您所见,每个记录的值将为1 ,并且收入大于1000000 (否则为0),那么我们将得出总和。 The same goes with the other column. 另一列也是如此。

Thanks to this StackOverflow question. 感谢这个StackOverflow问题。 You'll find this when you search "sql conditional count" in google. 当您在Google中搜索“ sql条件计数”时,会发现此问题。

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

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