【问题标题】:How to use the result of a query as the input for another query?如何使用查询的结果作为另一个查询的输入?
【发布时间】:2015-03-18 08:53:39
【问题描述】:

我想将一个选择查询的结果用作另一个选择查询的输入值。

这是一个例子:

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

返回一个包含 2 列的表格 姓氏

  • 托尼·丹扎
  • 托尼·贝内特

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

select * from Subscription where user='Danza';

是否可以使用占位符/公式代替手动输入“Danza”?比如:

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

我有 8 个选择查询,这些查询取决于先前选择查询的结果,所以我不确定连接是否可行。即姓名 > 姓氏 > 订阅 > readerID > deviceId > etc

我正在尝试查找记录,然后将其删除。以下是我尝试使用的实际查询

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;

【问题讨论】:

  • 您可以这样做,但是 = 比较需要子查询中最多一行。如果可能返回多行,请使用 IN 或 EXISTS。
  • 你的意思是像一个子查询? select * from Subscription where user=(select user_name from People where name=@name);

标签: mysql sql


【解决方案1】:

通过加入:

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

通过 in 子句:

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

我希望这会有所帮助。

【讨论】:

  • 谢谢。你能给我一个使用 3 个语句的答案吗?即 2 in 子句?
猜你喜欢
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多