开发者

How do I make a sql query where fields are the result of a different query?

开发者 https://www.devze.com 2022-12-24 07:48 出处:网络
I have two tables, the first is like this: f1 | f2 | f3 | f4 ----------------- data.... the second contains info about the fields of the first:

I have two tables,

the first is like this:

f1 | f2 | f3 | f4
-----------------
data....

the second contains info about the fields of the first:

field | info
------------
 f1      a
 f2      b
 f3      a
etc.

I would like开发者_开发百科 to query the first table selecting the fields with a query on the second. So, for example, I might want to get data for fields where info is equal to "a", thus I would do "select f1, f3 from first_table". How do I do this programmatically? I was thinking about something along the lines of select (select fields from second_table where info='a') from first_table

Thanks Chris


You can't treat strings as field identifiers in SQL, just can't be done. The only way would be to first run the first query and then construct another SQL query based on the first's results.

Even so, sounds like you're doing things in a wrong way. Maybe you should describe your practical application so people can suggest better ways to approach it.


You will have to run the first query and use the data to construct a dynamic query that can then be run to get the data that you want. This is often used when you need a pivot query, where the number of fields is not known beforehand.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号