[英]mySQL - Querying a field from another table with the same id as in the current one
This is a quite complex project having specific reasons for the way it is setup, but for ease of learning purposes, I've replaced the subject with just names. 这是一个相当复杂的项目,其设置方式有特定的原因,但是为了便于学习,我仅用名称代替了该主题。
For example, I have two tables: 例如,我有两个表:
Servers (stores unique server names) 服务器 (存储唯一的服务器名称)
Clients (stores all the clients in the company) 客户 (存储公司中的所有客户)
server_id
(matches the unique id from servers
table) server_id
(与servers
表中的唯一ID匹配) What I'm trying to do is list the distinct server names from the first table, along with the number of clients that use each server id. 我想做的是列出第一个表中不同的服务器名称,以及使用每个服务器ID的客户端数量。 But instead of returning the server "id", I'd like to return the "name". 但是,我不想返回服务器“ id”,而是返回“名称”。 Right now I have this: 现在我有这个:
SELECT DISTINCT server_id, count(server_name) AS count
FROM clients
GROUP BY server_id
This returns the server id instead of the name. 这将返回服务器ID而不是名称。 How do I fix that? 我该如何解决? Complete beginner to SQL and mySQL by the way. 顺便说一下,完成了SQL和mySQL的初学者。
Try 尝试
SELECT s.server_id,
s.server_name,
COUNT(*) count_clients
FROM clients c JOIN servers s
ON c.server_id = s.server_id
GROUP BY s.server_id, s.server_name
Output: 输出:
| SERVER_ID | SERVER_NAME | COUNT_CLIENTS |
-------------------------------------------
| 1 | server1 | 2 |
| 2 | server2 | 4 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.