【问题标题】:Select from related tables从相关表中选择
【发布时间】:2020-07-16 04:47:23
【问题描述】:

所以在我的数据库中,我有 2 个相关的表: 这些字段是 id、name、price 和一个 int,所以我知道它们是否全部售出

水果

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

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

如果我想要所有出售的水果中的所有东西,并且只想要每个水果的第一张图片,该怎么办

【问题讨论】:

  • 如果有多张图片,你要哪张?

标签: mysql sql join greatest-n-per-group


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我了解您希望每个水果的第一张图片,first 被定义为: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
    

    【讨论】:

    • 所有工作都作为一个魅力 tyvm。使用 row_number 和 select min 有什么区别吗?就像性能一样
    猜你喜欢
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2015-11-03
    • 2016-05-01
    • 2014-12-11
    相关资源
    最近更新 更多