简体   繁体   中英

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

  • 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? 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. ie name > surname > subscription > readerID > deviceId > etc

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 :

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

I hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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