using subquery instead of the tablename

会有一股神秘感。 提交于 2019-12-12 15:30:01

问题


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?


回答1:


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;



回答2:


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.




回答3:


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.




回答4:


Try aliasing the subquery.

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


来源:https://stackoverflow.com/questions/5931549/using-subquery-instead-of-the-tablename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!