Select 来自相关表格

Select from related tables

所以在我的数据库中我有 2 个相关的表: 这些字段是 ID、名称、价格和一个整数,所以我知道它们是否全部售出

水果

|IDfruit| name  | price  | sold  |
|  1    |orange | 5      | 0
|  2    |apple  | 10     | 0
|  3    |grape  | 15     | 1
|  4    |lemon  | 7      | 1

主键是 IDfruit

图片

|IDimage| url        | idfruit_image
| 1     | image1.png |     1      
| 2     | image2.png |     1
| 3     | image3.png |     2
| 4     | image4.png |     3    
| 5     | image5.png |     4
| 6     | image6.png |     4 
| 7     | image7.png |     4 

IDimage 是主键,idfruit_image 是引用 IDfruit 的外键

我想要的结果是所有水果和每个水果的第一张图片。

所以我所做的是

select fruits.*, url , idfruit_image 
from fruits,images 
where IDfruit = idfruit_image;

这 return 所有水果和每个水果的所有图像,但我只想要每个水果的一张图像,我该如何实现?

如果我想要所有已售出水果的所有东西以及每个水果的第一张图片怎么办

我知道你想要每个水果的第一张图片,第一张被定义为:最小的图片idimage

如果您只想要图像的 url,相关子查询应该是一个可接受的解决方案:

select 
    f.*, 
    (
        select i.url 
        from images i 
        where i.idfruit_image = f.idfruit 
        order by i.idimage 
        limit 1
    ) url
from fruits f

如果你想要整个图像记录,一种选择是加入,然后用子查询过滤:

select f.*, i.*
from fruits f
inner join images i on i.idimage = (
    select min(i1.idimage) from images i1 where i1.idfruit_image = f.idfruit
)

最后:在 MySQL 8.0 中,您可以使用 row_number()

select *
from (
    select 
        f.*, 
        i.*, 
        row_number() over(partition by i.idfruit_image order by i.idimage) as rn
    from fruits f
    inner join images i on i.idfruit_image = f.idfruit
) t
where rn = 1

使用 GROUP BY 为每个水果获取一行,并使用聚合函数 select 其中一张图像。

SELECT f.*, MAX(url) AS url
FROM fruits AS f
LEFT JOIN images AS i ON f.idfruit = i.idfruit_image
GROUP BY f.idfruit