代码之家  ›  专栏  ›  技术社区  ›  axsuul

简单MySQL查询问题

  •  3
  • axsuul  · 技术社区  · 16 年前
    bins
    ----
    id      min      max
    1       1        20
    2       21       40
    3       41       60
    
    pictures
    --------
    id
    3
    11
    59
    

    基本上,我想选择最高的图片ID,然后从bin表中选择与其匹配的bin ID。例如,对于pictures.id=59(最高),我希望bins.id=3。有人能帮我回答这样的问题吗?类似的东西

    SELECT bins.id AS id
    FROM bins
        JOIN pictures.id 
        ON bins.min < MAX(pictures.id)
            AND bins.max > MAX(pictures.id)
    

    似乎不起作用。谢谢!

    3 回复  |  直到 16 年前
        1
  •  2
  •   Massimo Fazzolari    16 年前
    SELECT id 
    FROM bins
    WHERE min < (Select Max(id) from Pictures) 
      AND max > (Select Max(id) from Pictures) 
    

    希望它有帮助

    马克斯

        2
  •  1
  •   Charles Bretana    16 年前

    试试这个

       Select id From Bins
       Where (Select Max(id) From pictures)
           Between Min and Max
    
        3
  •  0
  •   martin clayton egrunin    16 年前

    如果bin限制(bin.min和bin.max)随着样本数据中的id而增加,则可以使用以下方法获取“max”图片id的bin id:

    SELECT MAX( bins.id )
    FROM   bins
    JOIN   pictures
    ON     bins.min <= pictures.id
    AND    bins.max >= pictures.id
    

    注意使用 <= => -否则,将有效排除肥料箱限值(例如picture.id=41与肥料箱不匹配)。

    也可以写:

    SELECT MAX( bins.id )
    FROM   bins
    JOIN   pictures
    ON     pictures.id BETWEEN bins.min AND bins.max
    

    这个 会破裂的 如果您的仓位限制没有用仓位ID排序。