1

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

text_post

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

media_post

+-------+------------+--------+---------+---------+---------------+---------+
|post_id|post_content|post_url|post_user|post_type|post_visibility|post_date|
+-------+------------+--------+---------+---------+---------------+---------+

在 text_postpost_content中是用户发布的文本数据,在 media_postpost_content中是与多媒体文件相关联的标题文本,因此基本上post_content是文本。所有列都是通用的,只有 post_url 在 media_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设置为空,因为只有multimedia_post那一列......而第二行来自multimedia_post因为有帖子的网址......

我怎样才能做到这一点?

4

3 回答 3

2

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

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选择 from text_post:这是为了排列两个 select 语句的列所必需的。

于 2013-04-08T13:12:05.623 回答
1

使用联合

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
于 2013-04-08T13:13:45.377 回答
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
于 2013-04-08T13:14:17.003 回答