2016-07-07 91 views
0

我有如下的數據。每名患者都有一個獨特的身份證明,藥物表明處方藥物在SQL中選擇行

Id drug 
1 abc 
1 ghi 
2 abc 
2 cde 
2 def 
3 ghi 
3 klm 

我想看看SQL中爲「ghi」患者開處方的藥物。結果應該是這樣的。

標識藥物

1 ABC

1 GHI

3 GHI

3 KLM

預先感謝。

+3

請告訴我們你到目前爲止嘗試過的。謝謝。 –

+0

由此我們的意思是代碼,而不是藥物 – Strawberry

回答

0

是這樣的東西你在找什麼?

SELECT id, drug FROM (SELECT id FROM Patients WHERE drug = 'ghi') AS T INNER JOIN Patients AS P ON T.id = P.id 

這將讓誰擁有「全球飢餓指數」,並從該列表返回到處方的患者ID和藥物的列表中的所有患者的名單。

0

你沒有提到你的表名。我猜它是處方

您的查詢期望:

select * from prescription where id in 
(select id from prescription where drug='ghi') 

這裏是如何我都做到了。

數據庫模式

create table prescription 
(
    id int, 
    drug varchar(100) 
); 
insert into prescription(id, drug) values(1, 'abc'); 
insert into prescription(id, drug) values(1, 'ghi'); 
insert into prescription(id, drug) values(2, 'cde'); 
insert into prescription(id, drug) values(2, 'def'); 
insert into prescription(id, drug) values(3, 'ghi'); 
insert into prescription(id, drug) values(3, 'klm'); 

查詢

select * from prescription where id in 
(select id from prescription where drug='ghi') 

結果

id drug 
1 abc 
1 ghi 
3 ghi 
3 klm 

如果你想測試我在線這裏是小提琴http://www.sqlfiddle.com/#!9/0a299/7/0

+0

謝謝。這樣可行。 –

+0

很高興聽到這個消息。當用戶收到他或她的問題的良好答案時,該用戶可以選擇「接受」答案。看看這裏:http://stackoverflow.com/help/accepted-answer – arsho