[英]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. 我必须遵循以下表格,我想加入它们,其中icd9中的sequence为1,并且每个科目在接纳表中都有一个hadm_id。 Each subject can have multiple hadm_id but I want those who only have 1 hadm_id.
每个主题可以有多个hadm_id,但我希望只有1个hadm_id的主题。 I also want subjects where the sequence value is 1.
我还希望序列值为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. 这样,您就可以进行分组,使用HAVING进行过滤,在一个子查询本身中进行排序和限制,然后使用icd9进行连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.