简体   繁体   中英

mysql joining two tables to get where certain column is a specific value

I have to following tables and I want to join them where sequence is 1 in icd9 and each subject has one hadm_id in the admissions table. Each subject can have multiple hadm_id but I want those who only have 1 hadm_id. I also want subjects where the sequence value is 1.

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    |       |
+------------+----------+------+-----+---------+-------+

My query is as follows. When I run it I get the error below

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;

I am not sure about how to fix this error. I tried several methods but I keep getting this.

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

Try this:

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;

That way, you are doing grouping, filter with HAVING, ordering and limiting in one subquery itself, and then joining with icd9.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM