简体   繁体   English

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

[英]How to use the result of a query as the input for another query?

I want to use the result from a select query as the input value for another select query. 我想将选择查询的结果用作另一个选择查询的输入值。

Here's an example: 这是一个例子:

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

Returns a table of 2 columns name surname 返回由2列组成的表的名称

  • Tony Danza 托尼·丹扎
  • Tony Bennett 托尼·贝内特

I then want to use the surname of the first record to look up a subscription. 然后,我想使用第一条记录的姓氏来查找预订。

select * from Subscription where user='Danza';

Is it possible to use a placeholder / formula instead of typing in 'Danza' manually? 是否可以使用占位符/公式代替手动输入“ Danza”? Something like: 就像是:

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

I have 8 select queries that depend on the result of the previous select queries so I'm not sure if joins are the way to go. 我有8个选择查询,这些查询取决于以前的选择查询的结果,因此我不确定联接是否可行。 ie name > surname > subscription > readerID > deviceId > etc 即名称>姓氏>订阅>读者ID>设备ID>等

I'm trying to locate records and then delete them. 我正在尝试查找记录,然后将其删除。 Here are the actual queries that I'm trying to use 这是我要使用的实际查询

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;

by join : 通过加入:

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 : 通过in子句:

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

I hope this will help. 我希望这将有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM