質問

my data in the mySQL DB looks like this (but not only this 4, i have many persons which are appearing more then once, but with different qualifications and different modified dates

the data i have in my database

Selection would be something like:

SELECT * FROM table where person_id=1 GROUP BY person_id

so, if i make this selection and i group by person_id i get something like this:

my result after selection an group by

is there any possibility to group by the person id, but to say: ok, give me the last modified qualification? normally i don't have the person_id in the where SQL statement.
so i want all persons from my selection but only the result with the last modified qualification
( I hope I explained it well eonough so you understand what the problem is )

(my selection is of course much more complicated then the one i showed, this is just for showing you what I'm doing)

役に立ちましたか?

解決

You can also use a subquery to return the max modified date for each person_id and then join that result to your table to get the rows with the max date:

select t1.id, 
  t1.person_id,
  t1.name,
  t1.qualification,
  t1.created,
  t1.modified,
  t1.version
from yourtable t1
inner join
(
  select person_id, max(modified) MaxMod
  from yourtable
  group by person_id
) t2
  on t1.person_id = t2.person_d
  and t1.modified = t2.maxmod

他のヒント

If you want the last modified entry of a specific person then just do

select * from table
where person_id = 1
order by modified desc
limit 1

EDIT

I misunderstood the question and i will update the answer

Try this (assuming you want the last modified qualification for each person):

SELECT 
   person_id,
   qualification
FROM 
   table as a
INNER JOIN (
   SELECT 
     person_id,
     MAX(modified) as za_date
   FROM 
     table
   GROUP BY 
     person_id
) as tmp 
  ON a.person_id = tmp.person_id
  AND a.modified = tmp.za_date

If you want the last modified qualification for all persons :

SELECT
   qualification
FROM
   table
WHERE modified = (
       SELECT 
           MAX(modified)
       FROM
           table  
   )
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top