I have implemented a version control with mysql (and php).
It looks like the following:
categories
-------------
| id | name |
|----|-------
| 1 | a
| 2 | b
| 3 | c
| 4 | d
-------------
revisions
----------------------
| id | cid | current |
|----|-----|----------
| 1 | 1 | 1 |
| 2 | 1 | NULL |
| 3 | 2 | NULL |
| 4 | 3 | 1 |
| 5 | 4 | NULL |
| 6 | 4 | 1 |
----------------------
Each category has multiple revisions assigned to it. A revision is set, if “current” is set to 1 (only one revision per category can be 1, all others are NULL). What I want now is to get every category, which has new reivisions (note, once a revision is submitted it is not set to current immedeately. this is done by a e.g. a moderator). My problem is now getting also each category, which only has one revision with current IS NULL
Therefore the expected result would be:
-------------
| category.id
|------------
| 1
| 2
-------------
all the best
edit://
My current solution is:
SELECT categories.* FROM categories
JOIN revisions as t1 ON
(
t1.cid = categories.id
t1.current IS NULL
)
JOIN revisions as t2 ON
(
t2.id != t1.id
t2.current IS NOT NULL
t2.cid = categories.id
)
WHERE t1.id > t2.id
i made an SQL Fiddle Demo with a different table structure that will fit your needs
Foreign Key Relations
Check Relations on DELETE
SQL Fiddle DEMO