我正在编写一个能够同时检查多行的查询。如果相同用户记录的组合提供了我需要的足够信息,即使每个记录都没有提供我需要的足够信息,也会认为用户已通过。
例如: 有两张桌子。
一个是保留用户个人信息的“用户”:
id client_id first_name last_name date_of_birth ssn address
另一个是“实验室”,它保存用户的医疗测试信息: id external_source_id user_id date wbc rbc hemoglobin hematocrit mcv mch mchc rdw plateletcount
一个用户在用户表中只能有一条记录,但在labs表中可能有多条记录。我想要做的是检查属于同一用户的用户的多个实验室记录,看看这些记录的组合是否提供了我需要的必要信息。如果是,即使任何单个实验室记录未提供足够的信息,也会通过该用户。例如,必要的信息包括胆固醇,ldl,甘油三酯,葡萄糖。如果用户有两个实验室记录,一个记录提供胆固醇(NOT NULL)和ldl(NOT NULL),另一个记录提供甘油三酯(NOT NULL),葡萄糖(NOT NULL)。他被认为通过了。
如何编写能够执行此操作的查询?
我目前的查询是这样的:
SELECT users.id AS user_id, users.first_name, users.last_name, clients.name AS client,
users.social_security_number AS ssn, users.hiredate, hra.id AS hra_id, hra.date AS hra_date, hra.maileddate AS hra_maileddate,
screening.id AS screening_id, screening.date AS screening_date, screening.maileddate AS screening_maileddate
FROM users
INNER JOIN clients
ON(
users.client_id = clients.id
)
INNER JOIN hra
ON(
users.id = hra.user_id
)
LEFT JOIN labs
ON(
users.id = labs.user_id
)
WHERE users.client_id = '1879'
AND hra.date BETWEEN '2011-07-01' AND '2011-11-15'
AND hra.maileddate IS NOT NULL
AND labs.date BETWEEN '2011-05-15' AND '2011-11-15'
AND labs.maileddate IS NULL
AND labs.cholesterol IS NOT NULL
AND labs.ldl IS NOT NULL
AND labs.triglycerides IS NOT NULL
AND (labs.glucose IS NOT NULL OR labs.ha1c IS NOT NULL)
GROUP BY users.id
答案 0 :(得分:1)
这将选择示例中的所有用户
select u.*
from user u
join lab l1 on l1.user_id = u.id and l1.wbc is not null
join lab l2 on l2.user_id = u.id and l2.hemoglobin is not null
join lab l3 on l3.user_id = u.id and l3.plateletcount is not null
-- etc for other fields that need to be not null
即使相同的记录有多个所需的列,或者这些值分布在各行中,这也会有效。
如果您还想要实验室值,只需select u.*, l1.wbc, l2.hemoglobin, ... etc
答案 1 :(得分:0)
如果您想要通过的用户:
您可以使用IN with AND子句
Select u.* from user u
where
u.user_id in (select user_id from lab where wbc is not null) and
u.user_id in (select user_id from lab where hemoglobin is not null) and
u.user_id in (select user_id from lab where plateletcount is not null);
如果你想要那些不感兴趣的用户
您可以使用IN with OR子句
Select u.* from user u
where
u.user_id in (select user_id from lab where wbc is null) OR
u.user_id in (select user_id from lab where hemoglobin is null) OR
u.user_id in (select user_id from lab where plateletcount is null);
我希望这是有道理的:)