Question

well FYI this is my first post, so i don't really know about the rule here,

i just stuck in selecting data from my db, here's some of my data.

Table (Monster_card)
mons_card_id | Level
    1           1
    2           1
    3           1
    4           1
Table (Monster_registration)
mons_reg_id |mons_card_id | status      | time(timestamp)
    1            1         "REGISTER"    "2012-07-09 12:00:00"
    2            1         "UNREGISTER"  "2012-11-01 12:49:01"
    3            2         "REGISTER"    "2012-11-03 12:49:01"
    4            3         "REGISTER"    "2012-11-04 12:49:01"

my current query is =

select a.mons_card_id from monster_card a, monster_registration b
where b.status = "REGISTER"

;

my desired result = by the data above, the result should only mons_card_id 2 & 3. but in my current result, mons_card 1 also shown up.

sorry for the incomplete post before.

any suggestion?

Was it helpful?

Solution

You can use NOT EXISTS to make sure there are no more recent records with a status other than "REGISTER" for a given mons_card_id

SELECT mons_card_id
FROM monster_registration M
WHERE M.status = 'REGISTER' AND NOT EXISTS (
    SELECT 1 FROM monster_registration R
    WHERE R.mons_card_id = M.mons_card_id
        AND R.time > M.time 
        AND R.status <> 'REGISTER'
)

Working SqlFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top