3
bins
----
id      min      max
1       1        20
2       21       40
3       41       60

pictures
--------
id
3
11
59

Basically, I want to select the highest picture Id and then select from the bin table the bin id it matches. For example, for a pictures.id = 59 (highest), I want bins.id = 3. Can anyone help me with such a query? Something like

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

doesn't appear to work. Thanks!

3 Answers 3

2
SELECT id 
FROM bins
WHERE min < (Select Max(id) from Pictures) 
  AND max > (Select Max(id) from Pictures) 

Hope it helps

Max

Sign up to request clarification or add additional context in comments.

1 Comment

Does MySQL require the ANY keyword? Because the subqueries will only return one value, so ANY, ALL, SOME, or nothing should mean the same thing here, no?
1

Try this

   Select id From Bins
   Where (Select Max(id) From pictures)
       Between Min and Max

Comments

0

If the bin limits (bin.min and bin.max) increase with id as in the sample data, then the bin id for the 'max' picture id can be obtained using:

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

Note the use of <= and => - otherwise the bin limit values will be effectively excluded (e.g. picture.id=41 would not match a bin).

Can also be written:

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

This will break if your bin limits are not sorted with bin id.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.