Jump to content

can I select max(id) using WHERE?


stevieontario

Recommended Posts

Morning PHPFreaks, this might be an easy problem to solve but I'm stumped.

 

I have two tables:

Source (id, filename, filedatetime)

Perform (performid, sourceid, machinename, machinetype, output)

 

Every hour one new row will go into Source (source.id is an auto-incremented primary key), and 100 new rows will go into Perform. The 100 new rows that go into Perform will each have the same sourceid (which is of course the same number as source.id).

 

My query: I want to select perform.output for each hour, and group the results by machinetype, and order the results by output. Then I can look at output trends for specified time periods.

 

My problem: I want to query perform for output in the most recent hour, i.e., to retrieve the most recent id. So far the only way I have been able to do that is like so:

SELECT machinetype AS "Machine type", format( sum( output ) , 0 ) AS "Machine output", 
FROM perform
WHERE sourceid =790
GROUP BY machinetype
ORDER BY sum( output ) DESC

 

This of course requires that I know that the last sourceid is indeed 790.

 

My question: how can I achieve the same result without having to learn the specific sourceid?

 

Thanks in advance!

 

 

Link to comment
Share on other sites

SELECT machinetype AS "Machine type", format( sum( output ) , 0 ) AS "Machine output",
FROM perform
CROSS JOIN
(SELECT MAX(id) AS sourceid FROM Source) AS sq
USING (sourceid)
GROUP BY machinetype
ORDER BY sum( output ) DESC

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.