简体   繁体   English

MySQL-从另一个表中查询与当前表相同的ID的字段

[英]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) 服务器 (存储唯一的服务器名称)

  • server_id (unique id) server_id(唯一ID)
  • server_name 服务器名称

Clients (stores all the clients in the company) 客户 (存储公司中的所有客户)

  • server_id (matches the unique id from servers table) server_id (与servers表中的唯一ID匹配)
  • .. other columns ..其他专栏

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 |

SQLFiddle SQLFiddle

暂无
暂无

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

相关问题 创建记录时,Mysql触发器将id从一列复制到同一表中的另一列 - Mysql trigger to copy id from one column to another in same table when record is created 从一个表到另一个表的INNER JOIN mysql,它基于相同ID的倍数 - INNER JOIN mysql from one table to another where its based on multiples of same id 如何从同一mysql数据库表中的另一个字段移动一个字段数据? - How to move one fields data from another field within same mysql database table? MYSQL将字段从一个表复制到另一表 - MYSQL Copy field from one table to another table PHP:从一个 mysql 表中获取最后一行的 id 号,并使用它来更新另一个表的第一行中的字段 - PHP: Taking the last row's id number from one mysql table and using it to update a field in the first row of another table 从另一个表查询产品后,在一个表中查询关联的图像 - Querying associated images in one table after querying products from another MySQL SELECT COUNT从一个表和ID从另一个表? - MySQL SELECT COUNT from one table and ID from another? 从一张表中取出 id 并在同一时间插入 - Take id from one table and insert in another same time 在MySQL php中将ID从一个表插入另一个表 - Insert ID from one table to another in MySQL php MySQL/PHP 如何从与同一行的另一个字段相关的字段中获取特定字段 id - MySQL/PHP how to get specific field id from field which is related with another field of the same row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM