2016-01-11 62 views
0

我必須添加以下表格,並且我想加入它們,其中icd9中的順序爲1,並且每個主題在招生表中有一個hadm_id。每個主題可以有多個hadm_id,但我想要那些只有1個hadm_id的人。我也想科目,其中序列值爲1mysql連接兩個表以獲得某些列是特定值的位置

icd9 
+-------------+--------------+------+-----+---------+-------+ 
| Field  | Type   | Null | Key | Default | Extra | 
+-------------+--------------+------+-----+---------+-------+ 
| subject_id | int(11)  | NO | MUL | NULL |  | 
| hadm_id  | int(11)  | NO | MUL | NULL |  | 
| sequence | int(11)  | NO |  | NULL |  | 
| code  | varchar(100) | NO |  | NULL |  | 
| description | varchar(255) | YES |  | NULL |  | 
+-------------+--------------+------+-----+---------+-------+ 

admissions 
+------------+----------+------+-----+---------+-------+ 
| Field  | Type  | Null | Key | Default | Extra | 
+------------+----------+------+-----+---------+-------+ 
| hadm_id | int(11) | NO | PRI | NULL |  | 
| subject_id | int(11) | NO | MUL | NULL |  | 
| admit_dt | datetime | NO |  | NULL |  | 
| disch_dt | datetime | NO |  | NULL |  | 
+------------+----------+------+-----+---------+-------+ 

我的查詢如下。當我運行它時,我得到下面的錯誤

select * from icd9 
    where sequence=1 as t1 
inner join 
    (select * from 
    (select subject_id, count(hadm_id) 
     as n_admissions from admissions 
     group by subject_id 
    ) as q1 
    where n_admissions = 1 
    order by subject_id limit 10) as q2 
AS t2 
ON t1.subject_id = q2.subject_id; 

我不確定如何解決此錯誤。我嘗試了幾種方法,但我一直在收到這個。

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as t1 
inner join 
    (select * from 
    (select subject_id, count(hadm_id) 
    ' at line 2 
+1

「WHERE」子句條件屬於所有表和連接。 'SELECT列FROM表加入othertable加入第三表WHERE條件' –

回答

1

試試這個:

select * 
from icd9 as t1 
inner join 
    (
    select subject_id 
    from admissions 
    group by subject_id 
    having count(hadm_id) = 1 
    order by subject_id 
    limit 10 
    ) as q2 
ON t1.subject_id = q2.subject_id and t1.sequence = 1; 

這樣一來,你在做分組,過濾器與具有,訂貨和一個子查詢本身的限制,然後,具有ICD9加盟。

+0

謝謝。這比我有更好的作品! – Sakib