簡體   English   中英

mysql連接兩個表以獲取某些列是特定值的地方

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

我必須遵循以下表格,我想加入它們,其中icd9中的sequence為1,並且每個科目在接納表中都有一個hadm_id。 每個主題可以有多個hadm_id,但我希望只有1個hadm_id的主題。 我還希望序列值為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    |       |
+------------+----------+------+-----+---------+-------+

我的查詢如下。 當我運行它時,出現以下錯誤

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

嘗試這個:

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;

這樣,您就可以進行分組,使用HAVING進行過濾,在一個子查詢本身中進行排序和限制,然后使用icd9進行連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM