数据库
首页 > 数据库> > MySQL查询联接和计数查询

MySQL查询联接和计数查询

作者:互联网

我正在尝试从Web应用程序的数据库中提取值,主持人可以在其中将公司添加到指定行业的列表中.此请求需要将每个行业的名称以及相关的活跃公司的数目一起列出,作为主持人的概述.

这些是我的表:

companies

 ____________________________________
| id |        company       | active |
|---------------------------|--------|
| 12 | Ton-o-Bricks Haulage |    0   |
| 16 | Roofs 'n' Walls      |    1   |
| 23 | Handy Services       |    1   |
| 39 | Carpentharry         |    1   |
|---------------------------|--------|

industries
 ________________________
| id |   industry  | mod |
|------------------|-----|
|  2 | Roofing     |  2  |
|  4 | Carpentry   |  2  |
|  7 | Handyman    |  2  |
|  8 | Haulage     |  2  |
|  9 | Electrician |  2  |
|------------------|-----|

links
 ___________________________
| id | industry | company  |
|--------------------------|
|  1 |     2    |    23    |
|  2 |     4    |    16    |
|  3 |     4    |    39    |
|  4 |     7    |    23    |
|  5 |     2    |    16    |
|  6 |     8    |    12    |
|--------------------------|

此查询有效,但不考虑不活跃的公司:

SELECT industries.id, industries.industry, count(links.id) as count FROM industries LEFT JOIN links on links.industry=industries.id WHERE industries.mod=2 GROUP BY industries.id

// -Results =======

2   Roofing     2
4   Carpentry   2
7   Handyman    1
8   Haulage     1
9   Electrician 0

我需要它来仅增加活跃公司的数量,但是当我尝试这样做时,我得到的结果很奇怪:

SELECT industries.id, industries.industry, count(links.id) as count FROM industries LEFT JOIN links on links.industry=industries.id, companies WHERE industries.mod=2 AND companies.active=1 GROUP BY industries.id

// -Results =======

2   Roofing     6
4   Carpentry   6
7   Handyman    3
8   Haulage     3
9   Electrician 0

我知道我缺少一些简单的东西,只是无法弄清楚是什么

谢谢,
史蒂文

解决方法:

您可能需要尝试以下方法:

SELECT      i.id, i.industry, count(l.id) as count
FROM        industries i
LEFT JOIN   (
               SELECT  l.industry, l.id
               FROM    links l
               JOIN    companies c ON (l.company = c.id AND c.active = 1)
            ) l ON (l.industry = i.id)
WHERE       i.mod = 2
GROUP BY    i.id, i.industry;

它应该返回以下结果:

+------+-------------+-------+
| id   | industry    | count |
+------+-------------+-------+
|    2 | Roofing     |     2 |
|    4 | Carpentry   |     2 |
|    7 | Handyman    |     1 |
|    8 | Haulage     |     0 |
|    9 | Electrician |     0 |
+------+-------------+-------+
5 rows in set (0.00 sec)

标签:join,count,left-join,mysql
来源: https://codeday.me/bug/20191105/1998037.html