我有两个用户帖子表,一个用于文本帖子,一个用于多媒体帖子,两个表格的结构如下。
表 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
因为帖子的网址......
我怎样才能做到这一点?
答案 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