从JOIN查询中检索唯一结果

时间:2016-06-08 03:03:38

标签: php mysql join

我有两张桌子,一张是'帖子',另一张是'图片'

帖子表

id |文章|

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

图片表

project_id | IMAGE_NAME |

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

我目前的疑问是:

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

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

我想要这样的结果,以避免多重结果。

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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

这将完全符合您的要求。

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]> 

答案 2 :(得分:0)

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