【问题标题】:Inner join duplicating data when fetched获取时内部连接复制数据
【发布时间】:2022-11-01 17:30:16
【问题描述】:

我只想获取一次发布数据,但我在另一个表中有 4 张图像。这是查询和输出

SELECT posts.id as post_id, posts.unique_id as post_unique_id, post_images.image_name as image_name FROM posts
JOIN post_images ON post_images.post_unique_id = posts.unique_id
WHERE post_images.post_unique_id = posts.unique_id

输出:

#post_id, #post_unique_id,    #image_name
'1',      'YBNkqOOn7',       '1667211631_controller.png'
'1',      'YBNkqOOn7',       '1667211631_response.png'
'1',      'YBNkqOOn7',       '1667211631_aaaaaaaa.png'
'1',      'YBNkqOOn7',       '1667211631_ajax_request.png'

但我想要的是只获取所有 4 张图像,但在 post_id 和 unique_id 中只有一次,不幸的是,我得到的是 post id 和唯一 id 的重复数据。 Is there any way to produce the output where I can get all 4 images but only once in the same value columns (post_id, unique_id)

或者

I just really have to make 2 queries (1 for post data and 1 for post_images)?

【问题讨论】:

    标签: mysql normalization


    【解决方案1】:

    您将这两个表连接两次,一次使用JOIN 子句,另一次使用WHERE 子句。这就是为什么你得到重复的日期。

    只需在没有两个 JOIN 的情况下运行查询,您将只获取一次数据,如下所示:

    SELECT posts.id as post_id, posts.unique_id as post_unique_id, post_images.image_name as image_name FROM posts
    JOIN post_images ON post_images.post_unique_id = posts.unique_id
    

    或者,如果您更喜欢带有 WHERE 子句的隐式 JOIN,请执行以下操作:

    SELECT posts.id as post_id, posts.unique_id as post_unique_id, post_images.image_name as image_name FROM posts, post_images
    WHERE post_images.post_unique_id = posts.unique_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 2020-08-07
      相关资源
      最近更新 更多