如何使用查询结果作为另一个查询的输入?

时间:2015-03-18 08:53:39

标签: mysql sql

我想使用select查询的结果作为另一个select查询的输入值。

以下是一个例子:

SET @name = 'Tony';
select * from People where name=@name;

返回包含2列的表 姓氏

  • Tony Danza
  • Tony Bennett

然后,我想使用第一条记录的姓氏来查找订阅。

select * from Subscription where user='Danza';

是否可以使用占位符/公式而不是键入“Danza'手动?类似的东西:

select * from Subscription where user=(result from first query);

我有8个选择查询,这些查询取决于先前选择查询的结果,因此我不确定是否可以使用联接。即名称>姓氏>订阅> readerID> deviceId>等

我试图找到记录然后删除它们。以下是我尝试使用的实际查询

SET @readerId=-7256784839031027017; // set manually
select * from Reader where readerId=@readerId;

SET @readersId=788216; // use the previous query's readerId column
select * from Reader_Device where READERS_ID=@readersId;

SET @deviceId=786527; // use the previous query's DEVICES_ID column
select * from Device where id=@deviceId;

SET @subscriptionValue='B1AA9B9FFBAE46918C079CAEC06EDC3B'; // use the previous query's deviceId column
select * from Subscription_attributes where KEY0='deviceId' and value=@subscriptionValue;

SET @subscriptionId=786618; // use the previous query's SUBSCRIPTION_ID column

delete from Installation where DEVICE_REF=@deviceId;
delete from Reader_Device where DEVICES_ID=@deviceId;
delete from Device where id=@deviceId;
delete from Subscription_attributes where KEY0='deviceId' and value=@subscriptionValue;
delete from Subscription_attributes where SUBSCRIPTION_ID=@subscriptionId;
delete from Subscription where id=@subscriptionId;
delete from Reader where readerId=@readerId;

1 个答案:

答案 0 :(得分:0)

加入:

select s.* from subscription s join people p on s.user = p.surname
where p.name = @name  /* modify as per your requirement */

by in clause:

select * from subscription
where user in(select surname from people where name = @name)

我希望这会有所帮助。