gpt4 book ai didi

mysql - 如何解决联合查询中记录数差异的问题

转载 作者:行者123 更新时间:2023-11-29 18:46:51 27 4
gpt4 key购买 nike

我有一份技术人员列表及其患者数量,当我单击技术人员时,我会得到患者列表及其详细信息。为此,我有一个查询返回每个技术人员的患者数量,另一个查询返回患者的记录。

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

技术人员_ID = 40 为 223 名患者

现在要查看该技术人员的患者列表,我有以下查询:

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),但存在重复的患者行...我需要帮助来了解如何为每个技术人员获取正确的患者数量而不重复。

有人可以帮忙吗?

最佳答案

我不确定我是否完全理解你的问题。不管怎样,我会尽量让事情变得简单。关于您的“计数”查询,您可以从这样的地方开始,我删除了归档,我认为对计数不应该有用。此查询应该为您提供避免多个 id 的计数(我在两个选择中使用 DISTINCT 并使用 UNION 来删除两个选择之间可能的重复项)。可能可以消除一些连接(但我不知道整个结构)。请遵循 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

关于mysql - 如何解决联合查询中记录数差异的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44561124/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com