根据表数据查询表和列

时间:2012-03-26 15:53:38

标签: sql oracle

在不知道表和列的名称的情况下,我想查询数据库检索表名和列名,然后查询给定的表。

我有一个类似于以下内容的Oracle数据库架构:

Item表:

Item_id, Item_type, 
=================
1   box
2   book
3   box

Book表:

Item_id, title,     author
===========================
2   'C# Programer', 'Joe'

Box表:

Item_id, Size
=====================
1,  'Large' 
3,  'X Large'

Column_mapping

Item_type, column_name, display_order
=====================================
box,       Size,    1
book,      title,   1
book,      author   2

Table_mapping表:

Item_type,  Table_name
========================
box,        Box
book,       Book

我想要一个SQL语句,它会产生如下结果:

Item_id, Item_type  column1  column2
====================================
1,  box,        'Large',       <null>
2,  book,       'C# Programer', 'Joe'
3,  box,        'X Large',     <null>

当我尝试简化查询时

select * 
from 
   (select Table_name
    from Table_mapping
    where Item_type = 'box')
where 
   Item_id = 1; 

我收到一个错误,即Item_id是无效的标识符

如果我尝试

select * 
from 
    (select Table_name
     from Table_mapping
     where Item_type = 'box');

我得到了

Table_name
===========
Box

我不知道该怎么办。

3 个答案:

答案 0 :(得分:3)

一种方法是连接两个表,然后在可以包含来自任一表的数据的列上使用coalesce

SELECT 
    i.Item_id,
    i.Item_type,
    COALESCE(b.title, bx.size)  column1,
     b.author   column2
FROM
   Item i
   LEFT JOIN Book b
   ON i.item_id = b.item_id
   LEFT JOIN Box bx
   ON i.item_id = bx.item_id

根据数据集的大小,您可能希望在连接上添加过滤器,例如

   LEFT JOIN Book b
   ON i.item_id = b.item_id
       and i.item_type = 'book'
   LEFT JOIN Box bx
   ON i.item_id = bx.item_id
       and i.item_type = 'box'

请参阅此SQLFiddle

如果您想根据table_mapping或column_mapping中的数据执行某些操作,则需要使用动态SQL

答案 1 :(得分:0)

基本上它是两个单独的查询。一个用于盒子,一个用于书籍。您可以使用union将结果集合并在一起。

select i.Item_id, i.Item_type, b.size, null
from Item i inner join Box b on i.Item_id=b.Item_id
where i.Item_type = "box"
UNION
select i.Item_id, i.Item_type, b.title, b.author
from Item i inner join Book b on i.Item_id=b.Item_id
where i.Item_type = "book"

答案 2 :(得分:0)

ORACLE实际上将表名和列名存储在其数据字典中,因此您无需单独维护这些数据。试试这个来获取表名:

SELECT table_name FROM user_tables;

然后执行此操作以获取每个表的列:

SELECT column_name FROM user_tab_columns WHERE table_name = 'MYTABLE';

一旦这样做,您将需要创建一个存储过程以执行动态SQL。我不认为你可以用普通的查询来做到这一点。

相关问题