[英]SQL - Select Columns from table where another table column value equals column name list
seen a lot of similar posts about parsing data based on values but nothing quite what I want to get the result column from one table that contains the column names for another table. 见过很多关于基于值解析数据的类似文章,但我所想的都不是我想从一个包含另一个表的列名的表中获取结果列。 For example:
例如:
Select [col1], [col2]
from Table1
where (select changes as (col#)
from table2)
The col# is a list of the column names I want from Table1. col#是我想要从Table1中获得的列名的列表。 Table2 changes column is a comma separated list.
表2更改列是用逗号分隔的列表。 I wanted to figure a way to be able to get each column from Table1 that's in the list from table2.
我想找到一种方法,能够从Table2列表中的Table1中获取每一列。 Any help is greatly appreciated.
任何帮助是极大的赞赏。
You'll have to create the query on-the-fly. 您必须即时创建查询。 You can either do this by:
您可以通过以下方式执行此操作:
changes
column into your calling application, then assembling a SQL query string from that data and execute it, or changes
列的数据提取到调用的应用程序中,然后从该数据中组装一个SQL查询字符串并执行它,或者 EXEC
ing it (or whatever your RDBMS's equivalent statement is). EXEC
(或与RDBMS等效的任何语句)。 Do be aware though that if the data in changes
ever comes from user input, you are in for a world of hurt. 但是请注意,如果
changes
的数据曾经来自用户输入,那么您将遭受changes
的伤害。
If you have control over the schema I would suggest to avoid this way of storing data. 如果您可以控制架构,建议不要使用这种存储数据的方式。 In general, comma-separated-lists are just unwieldy and fundamentally go against what a database is designed to do.
通常,用逗号分隔的列表很笨拙,并且从根本上违背了数据库的设计意图。 A change-table structure with one Boolean value for each column that could change
(id, col1_changed, col2_changed)
or with a single row for each changed column (id, changed_col_name)
would be much easier to use in a normal query. 在普通查询中,使用可更改的每一列具有一个布尔值
(id, col1_changed, col2_changed)
或每个更改的列具有一行(id, changed_col_name)
的更改表结构会容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.