mysql - 以下场景需要 SQL 查询

标签 mysql sql

我需要从下表(table1)中获取在同一日期加入(joining_date)部门 dept1 和 dept2 的 emp_id。

emp_id|| department||     joining_date
1     || dept3     ||     01/01/2014
1     || dept2     ||     01/01/2015
1     || dept1     ||     01/01/2015
2     || dept1     ||     01/01/2015
2     || dept2     ||     01/03/2015
3     || dept1     ||     01/02/2015
3     || dept2     ||     01/02/2015
3     || dept3     ||     01/02/2015
4     || dept1     ||     01/01/2014
4     || dept2     ||     01/01/2014
5     || dept1     ||     01/01/2014
5     || dept2     ||     01/01/2015
5     || dept3     ||     01/01/2016
6     || dept1     ||     01/01/2014
6     || dept2     ||     01/01/2014

所以,我应该得到 1,3,4 和 6。

最佳答案

在同一个表上使用 INNER JOIN。

SELECT `first`.* FROM table1 AS first
INNER JOIN table1 AS `second`
        ON `first`.emp_id = `second`.emp_id 
                AND `second`.department = "dept2" 
                AND `second`.joining_date = `first`.joining_date
WHERE first.department = "dept1"

以 dept2 为例,您必须添加 dept3

关于mysql - 以下场景需要 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37803475/

相关文章:

mysql - 使用内容类型 (object_pk) 创建通用关系时出错

java - MySQL同时选择和更新表

c# - 如何执行更新查询?

mysql - 基于另一个表列值的动态表连接?

php - 如何检查mysql中是否使用了限制?

MYSQL-登录警告: Using a password on the command line interface can be insecure

Php MySQL 类中的数据

MySQL:如何查看表上的所有约束?

php - MySQL 中存储的二进制数据被损坏

MYSQL根据当前时间查询结果