【问题标题】:Retrieve unique results from JOIN query从 JOIN 查询中检索唯一结果
【发布时间】:2023-03-17 02:14:01
【问题描述】:

我有两张表,一张是“帖子”,另一张是“图片”

帖子表

标识 |文章 |

 1    |   post 1    |  
 2    |   post 2    |    
 3    |   post 3    |  

图片表

项目 ID |图像名称|

 1            |   img1    |  
 1            |   img2    |    
 2            |   img3    | 
 2            |   img4    |  
 3            |   img5    |  
 3            |   img6    |  

我目前的查询是这样的:

SELECT  * FROM `images`  RIGHT   JOIN `posts` ON images.project_id = posts.id 

但它显示了帖子表中的多个结果。

我想要这样的结果,以避免出现多个结果。

post 1 - img1
post 2 - img3
post 3 - img5

【问题讨论】:

  • 请显示您当前的结果。
  • 告诉我查询给你的答案。我想它会给你: 1-post 1 -1-img1 //1-post 1 -1-img2//2-post 2 -2-img3//2-post 2 -2-img4 //3-post 3 -3-img5 //3-post 3 -3-img6

标签: php mysql join


【解决方案1】:
SELECT  
  p.article, i.image_name 
FROM 
  `posts` p
JOIN (
  select
    i2.project_id, min(i2.image_name) as image_name
  from
    images i2 
  group by
    i2.project_id
) i
 on i.project_id=p.id

【讨论】:

    【解决方案2】:

    这将完全按照您的要求进行。

    SELECT `posts`.id, `posts`.`article`,`images`.`image_name` FROM `posts` INNER JOIN `images` ON `posts`.`id` = `images`.`project_id` GROUP BY id
    

    看看这个。

    MariaDB [fbb]> SELECT * FROM `posts`;
    
    +----+---------+
    | id | article |
    +----+---------+
    |  1 | post1   |
    |  2 | post2   |
    |  3 | post3   |
    +----+---------+
    3 rows in set (0.00 sec)
    
    MariaDB [fbb]> SELECT * FROM `images`;
    +------------+------------+
    | project_id | image_name |
    +------------+------------+
    |          1 | img1       |
    |          1 | img2       |
    |          2 | img3       |
    |          2 | img4       |
    |          3 | img5       |
    |          3 | img6       |
    +------------+------------+
    6 rows in set (0.00 sec)
    
    MariaDB [fbb]> SELECT `posts`.id, `posts`.`article`,`images`.`image_name` FROM `posts` INNER JOIN `images` ON `posts`.`id` = `images`.`project_id` GROUP BY id
        -> ;
    +----+---------+------------+
    | id | article | image_name |
    +----+---------+------------+
    |  1 | post1   | img1       |
    |  2 | post2   | img3       |
    |  3 | post3   | img5       |
    +----+---------+------------+
    3 rows in set (0.00 sec)
    
    MariaDB [fbb]> 
    

    【讨论】:

      【解决方案3】:
      SELECT * FROM posts RIGHT JOIN images ON posts.id = images.project_id group by posts.id
      

      使用group by Clasue 获得独特的结果。

      【讨论】:

      • 它可以工作,但我无法从图像表中提取字段。
      • @CPuser 你要获取哪张图片?
      • 从 image 表中 project_id = id (posts) 表我在 images 表中有一个名为 image_name 的字段
      • @CPuser 很高兴知道您是否接受答案,以便其他人可以轻松找到解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多