开发者

using subquery instead of the tablename

开发者 https://www.devze.com 2023-03-04 00:28 出处:网络
Table Meta: -------开发者_高级运维------------------------------ typetab_name newtab_news sportstab_sps
Table Meta:
-------开发者_高级运维------------------------------
type                  tab_name
new                   tab_news
sports                tab_sps

Table tab_news
------
id

Table tab_sps
-------------------
id
xx

Now I want to use

SELECT id 
  FROM (SELECT tab_name 
          FROM Meta 
         WHERE type = 'news');

But it does not work, any ideas?


SQL does not support a variable/etc for the table name -- the only means of supporting what you ask is by using dynamic SQL:

FOR i IN (SELECT tab_name
            FROM META m
           WHERE m.type = ?) LOOP
  EXECUTE IMMEDIATE 'SELECT * FROM '|| i.tab_name ||'';
END LOOP;


The syntax structure you are trying to use doesn't do what you want. What appears in the FROM clause is a data set. This might be a table or a view. In your case the data set is a subset of "Meta"; specifically the column "tab_name" for rows with the type of "news".

SELECT id 
  FROM (SELECT tab_name 
          FROM Meta 
         WHERE type = 'news');

SQL is basically set oriented. You seem to want the "tab_name" to return a 'pointer' or a reference to a data set. That suggests a more object oriented approach. Rather than a table_name, the select from Meta would return instances of an object and the wrapper would use a method on that object to extract the details. That would be more of

SELECT tab_name.getId()
FROM Meta
Where type = 'news';

But I'd need a more 'business terms' description of the problem before trying to guess what the object structures might look like.


I do not believe what you are trying to achieve is possible. If you are working with a programming language with this data, you could return the sub-query value first and then build a new SQL statement for the query you want. However, building a dynamic query inside SQL like this does not appear to be possible.

I think you need to take a step back and look at your database logic. There has to be a different way of doing this. For example, since each table had to have the same layout, maybe you could do a union all and then filter the data to only what you really want. You could do that at runtime with a sub-query. The process would have a significant overhead if it scaled to much, but it might solve your root issue. Basically, rethink your design. There is a way to accomplish your end goal but it isn't down this path.


Try aliasing the subquery.

select * from  (select tab_name from Meta where type='news') as my_sub_query;
0

精彩评论

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