创建多个表的视图每一个不同的列数 [英] Creating a VIEW from multiple tables each with a different number of columns

查看:196
本文介绍了创建多个表的视图每一个不同的列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要到多个表组合成一个查看。结果
我的理解是,如果列数是不同的,我们不能用 UNION 。结果
我该如何解决这个问题?

I want to combine multiple tables into one VIEW.
My understanding is that if the number of columns are different we cannot use UNION.
How do I solve this?

我有以下三个

1 表格名称 - 专辑

2 表格名称 - AlbumPictures

3 表格名称 - 故事

我想有3个表如下:(我可以使用INNER JOINS-好心纠正我,如果我错了,这样做部分)

I want to have 3 tables as follows:(i can do this part using INNER JOINS- kindly correct me if i am wrong)

有关的故事: StoryID,ALBUMID,StoryTitle,AlbumCover,投票

For Stories: StoryID,AlbumID,StoryTitle,AlbumCover,Votes

对于专辑: ALBUMID,ALBUMNAME,AlbumCover,投票

For Albums: AlbumID,AlbumName,AlbumCover,Votes

的图片: AlbumPictureID,投票

For Pictures: AlbumPictureID,Votes

我要合并从上面的查询检索到一个查看和随机他们的所有行。由于列数在每一个结果集是不同的上面我能够将它们合并成一个查看

I want to merge all the rows retrieved from the above queries into one VIEWand shuffle them. As the number of columns are different in each of the result sets above am I able to combine them into one VIEW?

推荐答案

您可以做这样的事情。的 所有三个表给出空值类似列 的和的 表名列是识别带来的表数据

You can do something like this. All three tables are given similar columns with null values and TableName column is to identify the table which brings the data

编辑: 我不得不说,这是不正确的方法。我想告诉你如何工会表,但我想现在根据您的意见编辑时,它是越来越难看。

--Note: Vote is on all three table, I have selected from Stories
select s.storyId, a.albumId, s.storyTitle, null albumName, 
       ap.albumCover, s.votes , null albumPictureId, 'stories-albums-albumPics' tableName
from Stories s join Albums a on s.albumId = a.albumId 
               join AlbumPictures ap on a.albumid = ap.albumId

UNION ALL 
select null storyId, a.albumID, null storyTitle, a.albumName,
       ap.albumCover, a.votes, null albumPictureId, 'albums-albumPics' tableName
from Albums a join AlbumPictures ap on a.albumid = ap.albumId

UNION ALL --use required table here as well  
select null storyId, null albumId, null storyTitle, null albumName, 
       null albumCover, votes, albumPictureId, 'pictures' tableName 
from Pictures 

这篇关于创建多个表的视图每一个不同的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆