2013-04-04 111 views
1

我需要在一個查詢中返回兩個查詢的結果。我讀過其他文章,不知道這是否應該是內部連接。Mysql中的一個查詢(內連接?)

我想這兩個查詢:

MariaDB [servers]> select * from servers; 
+----+------------+---------+------------+ 
| id | servername | ip  | returncode | 
+----+------------+---------+------------+ 
| 1 | server1 | 0.0.0.0 | 0   | 
| 2 | server2 | 0.0.0.0 | 1   | 
| 3 | server2 | 0.0.0.0 | 0   | 
| 4 | server3 | 0.0.0.0 | 0   | 
| 5 | server3 | 0.0.0.0 | 4   | 
| 6 | server3 | 0.0.0.0 | 4   | 
| 7 | server3 | 0.0.0.0 | 4   | 
+----+------------+---------+------------+ 

MariaDB [servers]> select servername,count(returncode) from servers where returncode<>0 group by servername; 
+------------+-------------------+ 
| servername | count(returncode) | 
+------------+-------------------+ 
| server2 |     1 | 
| server3 |     3 | 
+------------+-------------------+ 

弄成這個樣子:

MariaDB [servers]> select ????????? 
+----+------------+---------+------------+-------------------+ 
| id | servername | ip  | returncode | count(returncode) | 
+----+------------+---------+------------+-------------------+ 
| 1 | server1 | 0.0.0.0 | 0   | 0     | 
| 2 | server2 | 0.0.0.0 | 1   | 1     | 
| 3 | server2 | 0.0.0.0 | 0   | 1     | 
| 4 | server3 | 0.0.0.0 | 0   | 3     | 
| 5 | server3 | 0.0.0.0 | 4   | 3     | 
| 6 | server3 | 0.0.0.0 | 4   | 3     | 
| 7 | server3 | 0.0.0.0 | 4   | 3     | 
+----+------------+---------+------------+-------------------+ 

是否有人可以幫助我瞭解如何做到這一點?我覺得這是一個內部聯接,但是我不知道我理解這個概念,完全..

回答

1

您可以使用子查詢來獲得returncode每個服務器的數量,然後使用LEFT JOINservers表得到結果:

select s.id, s.servername, s.ip, s.returncode, 
    coalesce(c.totalcount, 0) TotalCount 
from servers s 
left join 
(
    select servername, count(returncode) TotalCount 
    from servers 
    where returncode<>0 
    group by servername 
) c 
    on s.servername = c.servername; 

SQL Fiddle with Demo

我選擇了一個LEFT JOIN所以你將返回所有行從表servers即使沒有在子查詢匹配的行。

+0

這工作完美。謝謝! – user2246993 2013-04-04 23:07:40

+0

@ user2246993不客氣,高興地幫忙! – Taryn 2013-04-04 23:11:05