如何将一个select语句的结果用作另一个的变量?

时间:2013-03-14 22:18:26

标签: sql database variables

这就是我要做的事情

WITH 
loc_id AS ( // take the result of the following select statement
SELECT l.location_id
  FROM mopdb.lulocation l
  WHERE (l.location_short = 'FOO'))

SELECT d.device
  FROM mopdb.ludevice d
  LEFT JOIN lulocation l ON (d.location_id = l.location_id)
  WHERE (d.location_id = loc_id) //use it here 

2 个答案:

答案 0 :(得分:1)

如果您尝试使用公用表表达式,那么loc_id将是一个可以像子查询一样使用的表,因此您可以执行以下操作:

with loc_id as (
    select l.location_id
    from mopdb.lulocation l
    where (l.location_short = 'FOO')
) select
    d.device
from mopdb.ludevice d
left join lulocation l on d.location_id = l.location_id
where d.location_id = (select location_id from loc_id);
然而,

变量在SQL的每个方言中都会有不同的语法,因此它在很大程度上取决于您使用的产品。

答案 1 :(得分:1)

丑陋,但是:

   SELECT d.device
      FROM mopdb.ludevice d
      LEFT JOIN lulocation l ON d.location_id = l.location_id
      WHERE d.location_id = 
       (
        SELECT x.location_id
        FROM mopdb.lulocation x
        WHERE (x.location_short = 'FOO')
      )