2016-01-11 29 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