我有一份技术人员名单及其患者人数,当我点击技术人员时,我会得到患者名单及其详细信息。 为此,我有查询返回每个技术人员的患者数量,另一个返回患者的记录。
SELECT *, SUM(Rcount) as Number_of_patients
FROM
(
SELECT users.users_id, users.name, patients.patients_id, count(*) as Rcount
FROM pecs
INNER JOIN users ON pecs.techniciens_id = users.users_id
INNER JOIN titles ON users.titles_id = titles.titles_id
INNER JOIN patients ON patients.patients_id = pecs.patients_id
GROUP BY users_id
UNION ALL
SELECT users.users_id, users.name, patients.patients_id, count(*) as Rcount
FROM followup
INNER JOIN users ON followup.technician_id = users.users_id
INNER JOIN titles ON users.titles_id = titles.titles_id
INNER JOIN pecs ON pecs.pecs_id = followup.pecs_id
INNER JOIN patients ON patients.patients_id = pecs.patients_id
GROUP BY users_id
)x
GROUP BY users_id ORDER BY last_name ASC
结果是:
users_id | name | Number_of_patients
40 | ABABAB | 223
这是223名技术员_ID = 40
的患者现在,要查看此技术人员的患者列表,我有以下疑问:
SELECT *
FROM
(
SELECT patients.patients_id, patients.name
FROM pecs
LEFT JOIN users ON pecs.techniciens_id = users.users_id
LEFT JOIN titles ON users.titles_id = titles.titles_id
INNER JOIN patients ON patients.patients_id = pecs.patients_id
WHERE pecs.techniciens_id = 40
#GROUP BY patients_id
UNION ALL
SELECT patients.patients_id, patients.name
FROM followup
LEFT JOIN users ON followup.technician_id = users.users_id
LEFT JOIN titles ON users.titles_id = titles.titles_id
LEFT JOIN pecs ON pecs.pecs_id = followup.pecs_id
INNER JOIN patients ON patients.patients_id = pecs.patients_id
WHERE followup.technician_id = 40
#GROUP BY patients_id
)x
GROUP BY patients_id ORDER BY last_name ASC
现在,我获得了相同数量的记录(223),但是有一排重复的患者...我需要帮助,了解如何为每位技术人员获得正确数量的患者而无需重复。
有人可以帮忙吗?
答案 0 :(得分:0)
我不确定我完全理解你的问题。无论如何,我会尽量让事情尽可能简单。关于你的“计数”查询,你可以从这样的东西开始,在那里我删除了我认为不应该用于计数的文件。这个查询应该给你计数避免多个id(我在两个select和UNION中使用DISTINCT来删除两个select之间可能的重复)。可能是某些连接可以被淘汰(但我不知道整个结构)。请关注Tim B.关于发布问题的格式和关注的建议。
SELECT USERS_ID, COUNT(*) AS PATIENTS_COUNT
FROM (
SELECT DISTINCT USERS.USERS_ID, PATIENTS.PATIENTS_ID
FROM PECS
INNER JOIN USERS ON PECS.TECHNICIENS_ID = USERS.USERS_ID
INNER JOIN TITLES ON USERS.TITLES_ID = TITLES.TITLES_ID
INNER JOIN PATIENTS ON PATIENTS.PATIENTS_ID = PECS.PATIENTS_ID
UNION
SELECT DISTINCT USERS.USERS_ID, PATIENTS.PATIENTS_ID
FROM FOLLOWUP
INNER JOIN USERS ON FOLLOWUP.TECHNICIAN_ID = USERS.USERS_ID
INNER JOIN TITLES ON USERS.TITLES_ID = TITLES.TITLES_ID
INNER JOIN PECS ON PECS.PECS_ID = FOLLOWUP.PECS_ID
INNER JOIN PATIENTS ON PATIENTS.PATIENTS_ID = PECS.PATIENTS_ID
) A