我继承了一个数据库,该数据库已被用来挖掘数据。 有2个表是松散关联的-atm和dslams。 atm表包含与dslams“主机名”字段相关的“远程名”,“ rst”和“ CardNumber”字段。 atm表包含dslam卡的端口信息,而dslams表包含有关dslam卡本身的信息。 我的任务是打印出所有具有特定类型卡(dslams.model =“ 6256”)的位置(dslams.name)以及该卡上具有特定服务水平的所有端口的数量( atm.speed LIKE“ RI _%%09”或atm.speed LIKE“ RI %%1 %”)。 我精心制作了以下几乎可以奏效的语句...
SELECT distinct(dslams.name) AS Remote, Count(atm.speed) AS Customers, dslams.model
FROM dslams
LEFT JOIN atm
ON (dslams.hostname = CONCAT(atm.remotename,'-',atm.rst,'-S',atm.CardNumber)) AND (atm.speed LIKE "RI_%_%09" OR atm.speed LIKE "RI_%_%1_%")
GROUP BY dslams.name
HAVING dslams.model="6256"
ORDER BY dslams.name;
这会精确打印出我需要的位置(除了1个位置)。
即。
MariaDB [dsl]> SELECT distinct(dslams.name) AS Remote, Count(atm.speed) AS Customers, dslams.model
-> FROM dslams
-> LEFT JOIN atm
-> ON (dslams.hostname = CONCAT(atm.remotename,'-',atm.rst,'-S',atm.CardNumber)) AND (atm.speed LIKE "RI_%_%09" OR atm.speed LIKE "RI_%_%1_%")
-> GROUP BY dslams.name
-> HAVING dslams.model="6256"
-> ORDER BY dslams.name;
+---------+-----------+-------+
| Remote | Customers | model |
+---------+-----------+-------+
| ANTH-C2 | 1 | 6256 |
| BETY-C2 | 1 | 6256 |
| BHOT-C2 | 6 | 6256 |
| BNSH-C2 | 1 | 6256 |
| BUG2-C2 | 1 | 6256 |
| CCRK-C2 | 0 | 6256 |
...
| STLN-C2 | 1 | 6256 |
| SUMR-C2 | 2 | 6256 |
...
| WGRV-C2 | 0 | 6256 |
+---------+-----------+-------+
63 rows in set (0.34 sec)
由于某种原因,其中一个位置未被计数-STWL-C2。
MariaDB [dsl]> SELECT distinct(name), model FROM dslams WHERE model="6256" order by name;
+---------+-------+
| name | model |
+---------+-------+
| ANTH-C2 | 6256 |
| BETY-C2 | 6256 |
| BHOT-C2 | 6256 |
| BNSH-C2 | 6256 |
| BUG2-C2 | 6256 |
| CCRK-C2 | 6256 |
...
| STWL-C2 | 6256 |
...
| WGRV-C2 | 6256 |
+---------+-------+
64 rows in set (0.00 sec)
STWL-C2位置与其他位置之间的表没有区别,因此应打印为0。
有人可以帮我弄清楚为什么错过这1个位置吗?
任何帮助或指导都将不胜感激,因为我是一名菜鸟SQL程序员,她试图尽我所能来理解这一点。
最好的问候, 乔
答案 0 :(得分:0)
不要使用HAVING dslams.model = '6256'
,将其放在WHERE
子句中。当您使用HAVING
时,它将过滤之后分组。按name
分组时,结果可以包含该分组中任何行的model
,并且不一定选择model = '6256'
。
SELECT dslams.name AS Remote, Count(atm.speed) AS Customers, dslams.model
FROM dslams
LEFT JOIN atm
ON (dslams.hostname = CONCAT(atm.remotename,'-',atm.rst,'-S',atm.CardNumber)) AND (atm.speed LIKE "RI_%_%09" OR atm.speed LIKE "RI_%_%1_%")
WHERE dslams.model = '6256'
GROUP BY dslams.name
ORDER BY dslams.name;