简体   繁体   English

MySQL从两个表中选择查询

[英]MySQL select query from two tables

I have two tables: users and works 我有两个表: 用户作品

I need write select query for count different names from users table where work_status = 1 from works table 我需要写选择查询计算来自用户表的不同名称,其中来自工作表的work_status = 1

在此处输入图片说明

The total is : 3 John, 1 Tom 总计为 :3约翰,1汤姆

I need get result: 我需要得到结果:
John 2 ( 2 because one John work_status = 0 ant this not counting ) 约翰2( 2因为一个约翰work_status = 0 ant这不算数
Tom 1 汤姆1

I have write select that can count different names, just need compared work_status.. 我写了可以选择不同名称的select,只需要比较work_status。

SELECT name,COUNT(*) as num FROM users GROUP BY name

My query return: 我的查询返回:

在此处输入图片说明

There is a problem in your question. 您的问题有问题。 So here you have two solutions. 因此,这里有两个解决方案。

If there are three different John working on the company, this is your query 如果有三个不同的约翰在公司工作,这是您的查询

SELECT u.name, COUNT(*) as num 
FROM users u INNER JOIN works w ON w.user_id = u.id 
WHERE w.work_status = 1
GROUP BY u.name, u.id

If there are only one John working in the company, your query is this one: 如果公司中只有约翰一个人在工作,您的查询就是这个:

SELECT u.name, COUNT(*) as num 
FROM users u INNER JOIN works w ON w.user_id = u.id 
WHERE w.work_status = 1
GROUP BY u.name

Note: If three John are the same person, you should delete the 2 last and on the works table change user_id = 3 and user_id = 4 for user_id = 1 注意:如果三个约翰是同一个人,则应删除最后两个,然后在works表上将user_id = 3user_id = 4更改为user_id = 1

This one should do the job: 这应该做的工作:

SELECT users.name,SUM(works.work_status) as num 
  FROM users,works 
  WHERE users.id=works.id 
  GROUP BY name

This is a simple JOIN query: 这是一个简单的JOIN查询:

  SELECT u.name, COUNT(*) num
    FROM users u
    JOIN works w
      ON w.user_id = u.id
     AND w.work_status = 1
GROUP BY u.name
SELECT 
  users.`name`,
  COUNT(*) num 
FROM
  users,
  works 
WHERE users.`id` = works.`user_id` 
  AND works.`work_status` = 1 
GROUP BY users.`name` ;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM