2011-09-07 61 views
1

我正在編寫能夠檢查同一用戶的多行的查詢。如果同一用戶記錄的組合不能提供我需要的信息(請記住它是用戶擁有的所有記錄的組合,而不是一個記錄),則認爲用戶已通過。如何選擇多行的組合(MySQL)

例如:有兩個表格。

一種是「用戶」,它保留用戶的個人信息:

id client_id first_name last_name date_of_birth ssn address 

另一種是「篩選」,這使用戶的醫療測試信息:

id user_id date cholesterol ldl hemoglobin triglycerides mcv glucose 
mchc ha1c plateletcount. 

一個用戶只能有一個記錄在用戶表中,但在篩選表中可能有多個記錄。我想要做的是檢查屬於同一用戶的用戶的多個篩選記錄,看看這些記錄的組合是否提供了我需要的必要信息。如果否,則選擇用戶。例如,必要的信息包括膽固醇,ldl,甘油三酯,葡萄糖或。如果用戶有兩個篩選記錄,一個記錄提供cholesterol(NOT NULL),另一個提供triglycerides(NOT NULL),glucose(NOT NULL)ha1c(NOT NULL)。他被選中是因爲ldl缺失。

如何編寫能夠做到這一點的查詢?我嘗試了內部連接,但似乎不起作用。這裏有一些要求。對於膽固醇,ldl和甘油三酯,只要其中一個缺失,應該選擇用戶。但是對於葡萄糖和ha1c,僅當兩者都缺失時才選擇用戶。

一個我想查詢的是這樣的:

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, group_concat(screening.glucose), group_concat(screening.ha1c) 
    FROM users 
    INNER JOIN clients 
    ON(
     users.client_id = clients.id 
     ) 
    INNER JOIN hra 
    ON(
     users.id = hra.user_id 
     AND hra.date BETWEEN '2011-07-01' AND '2011-11-15' 
     AND hra.maileddate IS NOT NULL 
     ) 
    LEFT JOIN screening 
    ON(
     users.id = screening.user_id 
    AND screening.date BETWEEN '2011-05-15' AND '2011-11-15' 
    AND screening.maileddate IS NULL 
    AND (screening.cholesterol IS NULL 
     OR screening.ldl IS NULL 
     OR screening.triglycerides IS NULL) 
    AND screening.glucose IS NULL 
    AND screening.ha1c IS NULL 
    AND (screening.weight IS NULL 
     OR screening.systolic IS NULL 
     OR screening.diastolic IS NULL) 
    ) 
    WHERE users.client_id = '1879'  


    GROUP BY users.id 
+0

您只關心篩選記錄是否爲「NOT NULL」,或者您是否真的需要其內容?因爲您總是可以將Users表留給加入子查詢的用戶ID的Screening表,並獲得每個其他字段的MAX。如果該UserID的所有記錄都爲NULL,則它將僅返回一個NULL字段。這會滿足嗎? – mwan

+0

[如何檢查多行記錄組合(MySQL)]的可能的重複](http://stackoverflow.com/questions/7335781/how-to-check-combination-of-records-from-multiple-rowsmysql) –

回答

0

我認爲你必須去與在WHEREEXISTS()子查詢。像

SELECT ... 
FROM users 
INNER JOIN clients ON(users.client_id = clients.id) 
INNER JOIN hra ON(...) 
WHERE users.client_id = '1879' 
    AND(EXISTS(SELECT 1 FROM screening WHERE(users.id = screening.user_id)AND(...))) 

NOT EXISTS,這取決於你如何編寫你的標準。