如何加入mysql?

inkz8wg9  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(224)

总之,我面临加入mysql的问题。我想得到一个计数唯一数量的结果 staff_id 使用分组依据的字段。如果我运行这个查询,一步就能得到我想要的结果。

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 但结果是重复的。 ``SELECTtbl_warning.id,tbl_warning.staff_id,tbl_warning.note,tbl_warning.warning_date,tbl_employment.com_idascomid,tbl_staff.name,tbl_staff.genderFROMtbl_warningJOINtbl_employmentONtbl_employment.staff_id=tbl_warning.staff_idJOINtbl_staffONtbl_staff.id=tbl_warning.staff_idHAVING (SELECTstaff_idFROMtbl_warningGROUP BYstaff_idHAVING (count(staff_id) > 1)); 我要唯一的结果相同的第一个屏幕截图。谢谢您!

brjng4g3

brjng4g31#

您应该联接到按计数查找匹配人员的子查询:

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;

相关问题