【问题标题】:How to combine rows of 2 tables having some columns same and some different如何组合具有相同和不同列的 2 个表的行
【发布时间】:2013-03-30 13:57:17
【问题描述】:

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

表格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 中是用户发布的文本数据,在 media_post post_content 中是与多媒体文件相关联的标题文本,所以基本上post_content 是文本。所有的列都是通用的,只有在 media_post 中的 post_url 不同,我想将这两个表的结果组合如下

+-------+------------+--------+---------+---------+---------------+---------+
|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,因为有帖子的网址...

我怎样才能做到这一点?

【问题讨论】:

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


    【解决方案1】:

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

    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 语句的列所必需的。

    【讨论】:

      【解决方案2】:

      使用联合

      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
      

      【讨论】:

        【解决方案3】:

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

         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
        

        【讨论】:

          猜你喜欢
          • 2021-01-13
          • 1970-01-01
          • 2020-05-13
          • 2013-02-14
          • 2020-01-23
          • 1970-01-01
          • 1970-01-01
          • 2020-11-17
          • 2021-10-18
          相关资源
          最近更新 更多