【问题标题】:Use the value from a field in a table as a select statement将表中字段的值用作选择语句
【发布时间】:2016-03-14 18:00:58
【问题描述】:

例如,我正在尝试弄清楚如何将表中的值用作选择语句

table1 包含: 列-cl1 价值 - 麻木

表2: 列 - 麻木 值 1,2,3,4

我想选择 cl1 (value: numb) 然后用它来运行一个语句

select numb from table2

到目前为止我已经使用了

select (select cl1 from table1) from table2;

这会返回 numb 4 次,但我想要实际值

我期望的输出是 1,2,3,4。

我希望查询从表 1 中进行选择,该表将返回字段名称,然后将该字段名称(numb)用作 select 语句的一部分,因此期望结束 sql 看起来像:

select numb from table2; 

但是 numb 将是 table1 中的任何内容;

【问题讨论】:

  • 您需要将 SQL 构建为字符串,然后他们立即执行
  • 老实说这里需要更多信息,您可以添加一些虚拟数据以及您期望输出的数据吗?你的问题有点模棱两可。
  • 我添加了更多信息希望对您有所帮助

标签: sql oracle oracle11g oracle10g


【解决方案1】:

您可以这样做,但您需要扩展您的表格以包含您选择的可能列的列表,每个源行每列一行。如果这是一个很大的可能性列表或一个大型数据集....好吧,它不会很漂亮。

例如:

With thedata as (
    select 1 row_id, 11 col1, 12 col2, 13 col3 from dual union all
    select 2 row_id, 21 col1, 22 col2, 23 col3 from dual union all
    select 3 row_id, 31 col1, 32 col2, 33 col3 from dual union all
    select 4 row_id, 41 col1, 42 col2, 43 col3 from dual )
, col_list as (
   select 1 col_id, 'col1' col from dual union all    
   select 2 col_id, 'col2' col from dual union all
   select 3 col_id, 'col3' col from dual )
select row_id, coldata
FROM  ( 
        -- here's where I have to mulitply the source data, generating one row for each possible column, and hard-coding that column to join to
        SELECT  row_id, 'col1' as col, col1 as coldata from thedata
        union all
        SELECT  row_id, 'col2' as col, col2 as coldata from thedata
        union all
        SELECT  row_id, 'col3' as col, col3 as coldata from thedata
      ) expanded_Data
JOIN col_list
  on col_list.col = expanded_data.col
where col_id = :your_id;

设置id为2并获取:

ROW_ID  COLDATA
1       12
2       22
3       32
4       42

所以是的,它可以完成,但不是真正动态的,因为您需要事先充分了解并硬编码您从表中提取的可能的列名值。如果您需要一个可以选择任何列或任何表的真正动态选择,那么您需要动态构建查询并立即执行。

编辑 - 添加此警告: 我还应该补充一点,这仅在所有可能的列都具有相同数据类型时才有效,或者您需要将它们全部转换为通用数据类型。

【讨论】:

    【解决方案2】:

    您可以使用一个变量来存储 numb 的值,然后在您的 SELECT 语句中重用它,如下所示:

    DECLARE @numb int
    SET @numb = (SELECT cl1 from table2)
    
    SELECT * from stat1 s WHERE s.numb = @numb
    

    【讨论】:

    • 我认为 OP 想从 table1 中选择列名,并将其注入他/她的查询中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    相关资源
    最近更新 更多