mysql - 如何加入mysql?
问题描述
所有,我在加入mysql时遇到问题。我想得到一个staff_id
使用 GROUP BY 计算唯一数量的字段的结果。如果我运行这个查询,我会一步一步得到我想要的结果。
SELECT id,staff_id,note,warning_date FROM tbl_warning GROUP BY staff_id HAVING (count(staff_id) > 0);
接下来我想加入另外两个表来获取诸如tbl_employment
. com_id
如comid
, tbl_staff
. name
, tbl_staff
. gender
但结果是重复的。
`SELECT` `tbl_warning`.`id`, `tbl_warning`.`staff_id`, `tbl_warning`.`note`, `tbl_warning`.`warning_date`,`tbl_employment`.`com_id` as `comid`, `tbl_staff`.`name`, `tbl_staff`.`gender` FROM `tbl_warning`
JOIN `tbl_employment` ON `tbl_employment`.`staff_id` = `tbl_warning`.`staff_id`
JOIN `tbl_staff` ON `tbl_staff`.`id` = `tbl_warning`.`staff_id`
HAVING (SELECT `staff_id` FROM `tbl_warning` GROUP BY `staff_id` HAVING (count(staff_id) > 1));
我想要独特的结果与第一个屏幕截图相同。谢谢!
解决方案
您应该加入一个子查询,该查询按计数查找匹配的人员:
SELECT
t1.id,
t1.staff_id,
t1.note,
t1.warning_date,
t2.com_id as `comid`,
t3.name,
t3.gender
FROM tbl_warning t1
INNER JOIN tbl_employment t2
ON t2.staff_id = t1.staff_id
INNER JOIN tbl_staff t3
ON t3.id = t1.staff_id
INNER JOIN
(
SELECT staff_id
FROM tbl_warning
GROUP BY staff_id
HAVING COUNT(*) > 1
) t
ON t.staff_id = t2.staff_id;
推荐阅读
- c++ - C++ lambda 按值捕获而不提前声明变量
- javascript - 评论值仅适用于第一篇文章
- javascript - 跳过不存在的对象(过滤器)React-Native
- flutter - PersistentBottomSheet 中的 WebView 未检测到垂直滚动
- c++ - “使用命名空间”来定义全局函数
- hadoop - hive 配置 hive.stats.fetch.partition.stats 不存在
- wso2 - Wso2 API 管理器 STATS_DB
- python - python中的MIN函数-为什么会出现这个错误?
- vba - 有没有办法为表单的上下文写入/编辑一个只读的 Recordset 并使用数据?
- c# - 刷新和清除 Oxyplot 模型