如何组合2个表的行,这些表具有相同和不同的列

时间:2013-04-08 13:07:15

标签: mysql sql database-design join union-all

我有两个用户帖子表,一个用于文本帖子,一个用于多媒体帖子,两个表格的结构如下。

text_post

+--------+--------------+-----------+-----------+-----------------+-----------+
| postid | post_content | post_user | post_type | post_visibility | post_date |
+--------+--------------+-----------+-----------+-----------------+-----------+

multimedia_post

+-------+------------+--------+---------+---------+---------------+---------+
|post_id|post_content|post_url|post_user|post_type|post_visibility|post_date|
+-------+------------+--------+---------+---------+---------------+---------+
text_post post_content中的

是由用户发布的文本数据,而在multimedia_post post_content中是与多媒体文件关联的标题文本,因此基本上post_content是文本问题。所有列都很常见,只有post_url在multimedia_post中不同,我想把这两个表的结果合并如下

+-------+------------+--------+---------+---------+---------------+---------+
|post_id|post_content|post_url|post_user|post_type|post_visibility|post_date|
+-------+------------+--------+---------+---------+---------------+---------+
|  1    |  some text | null   | 1       | <type>  | <visibility>  | <date>  |
+-------+------------+--------+---------+---------+---------------+---------+
|  1    | img_caption| <url>  | 1       | <type>  | <visibility>  | <date>  |
+-------+------------+--------+---------+---------+---------------+---------+
..and so on

此处返回的第一行来自text_post,因此post_url设置为null,因为只有multimedia_post具有该列...而第二行来自multimedia_post因为帖子的网址......

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:2)

您可以UNION ALL从两个SELECT返回“排队”的列,如下所示:

SELECT
    postid as post_id
,   post_content
,   null as post_url
,   post_user
... -- the rest of text_post columns included in the select
FROM text_post
UNION ALL
SELECT
    post_id
,   img_caption as post_content
,   post_url
,   post_user
... -- the rest of multimedia_post columns included in the select
FROM multimedia_post

注意如何从null as post_url中选择text_post:为了排列两个select语句的列,这是必要的。

答案 1 :(得分:1)

使用UNION

SELECT 
  postid, post_content, NULL, post_user, post_type, post_visibility, post_date 
FROM
  text_post
UNION
 SELECT 
  postid, post_content, post_url, post_user, post_type, post_visibility, post_date 
FROM
  multimedia_post

答案 2 :(得分:1)

你必须在两个表上使用全外连接

 select post_id,post_content,post_url,post_user,post_type,post_visibility,
 post_date from 
 text_post as tp, multimedia_post as mp 
 on tp.post_id = mp.post_id