I have tried this multiple distinct from MySQL and I cant seem to get anything to work... I have a table that is a history table. The appartments can be found many times fr开发者_如何学Com the same building with different status. I need to find the newest one for each appartment (the one with the highest id ORDER BY id)
id building appartment_id status
208 1 2 2
209 1 3 2
210 1 4 2
211 1 5 2
212 1 6 2
213 1 7 2
214 1 2 1
215 1 2 3
But how do I do that?! :S I have tried this:
SELECT *, GROUP_CONCAT(appartment_id, building)
FROM `ib30_history`
group by appartment_id, building
order by id DESC
It seems to work but im not sure that is the right way of doing it and the code that uses the output seems to make funny things running through the data so im not sure it really works!
SELECT yourtable.id, yourtable.building, yourtable.appartment_id, yourtable.status
FROM yourtable
INNER JOIN (
SELECT MAX(id) AS id
FROM yourtable
GROUP BY building, appartment_id
) AS child ON yourtable.id = child.id
Get rid of distinct and use something like:
GROUP BY building , appartment_id
What you're looking for is called GROUP BY
, and MySQL's documentation knows a lot about how it's to be used. At the timeI type this, the OP doesn't contain a query so I cannot give you an example...
SELECT a.*
FROM table_name a
INNER JOIN
(SELECT MAX(id) as max_id
FROM table_name
GROUP BY appartment_id) b
ON (b.max_id = a.id)
精彩评论