在SQL中选择行

时间:2016-07-07 23:19:57

标签: mysql

我的数据如下。每位患者都有一个独特的身份,药物表示处方药。

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

我想看看为患者开出的药物是什么?#34; ghi"在SQL中。结果应该是这样的。

Id药物

1 abc

1 ghi

3 ghi

3 klm

提前致谢。

2 个答案:

答案 0 :(得分:0)

这就是你要找的东西吗?

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

这将获得所有患有此病例的患者的清单。从该清单中返回一份给这些患者开具的ids和药物清单。

答案 1 :(得分: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

相关问题