Mam tabele config
Kod
+---------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| fieldid | int(10) | NO | PRI | 0 | |
| value | char(20) | NO | | NULL | |
| siteid | int(10) | NO | PRI | | |
+---------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| fieldid | int(10) | NO | PRI | 0 | |
| value | char(20) | NO | | NULL | |
| siteid | int(10) | NO | PRI | | |
+---------+----------+------+-----+---------+-------+
Oraz tabelę config_fields
Kod
+---------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-----------+------+-----+---------+----------------+
| id | int(5) | NO | PRI | NULL | auto_increment |
| name | char(80) | NO | UNI | NULL | |
+---------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-----------+------+-----+---------+----------------+
| id | int(5) | NO | PRI | NULL | auto_increment |
| name | char(80) | NO | UNI | NULL | |
+---------------+-----------+------+-----+---------+----------------+
Teraz orzypoścmy ze mamy przykladowe dane w tabeli config_fields
1 - language
2 - theme
3 - recordsPerPage
Oraz przykladowe dane w tabeli config
id - value - siteid
1 - pl - 0
1 - en - 2
2 - silverTheme - 0
3 - 15 - 1
3 - 20 - 0
Siteid to nic innego jak idetyfikator strony. Teraz muszę pobrać wszystkie pola konfiguracyjne z tabeli config które mają siteid równy mojej wartości a jeśli takich nie ma to odpowiadające im pola z siteid = 0;
Np dla siteid = 1 otrzymam
1 - language - pl (siteid=1)
2 - theme - silverTheme (siteid=0)
3 - recordsPerPage - 15 (siteid=1)
Dla siteid = 2 otrzymam
1 - language - en (siteid=2)
2 - theme - silverTheme (siteid=0)
3 - recordsPerPage - 20 (siteid=0)
Mam nadzieję, że dobrze to wytłumaczyłem

SELECT cf.id, cf.name, c.value, c.siteid FROM config_fields cf INNER JOIN config c ON c.fieldid=cf.id AND (c.siteid=2 OR c.siteid=0) GROUP BY id ORDER BY cf.id, c.siteid DESC;
Wszsytko działa jeśli rekordy w tabeli config są ustawione w kolejnosci: najpierw z siteid!=0 a później z siteid=0 Jeśli jest odwrotnie zawsze otrzymuję wartość domyślną. Jak temu zaradziać? Da się to jakoś posortowac?
EDIT:
Posiedziałem posiedziałem i wymyśliłem coś takiego:
SELECT cf.id, cf.name,c.value FROM config_fields cf, config c WHERE c.value=(SELECT c2.value FROM config c2 WHERE c2.fieldid = cf.id AND (c2.siteid=16 OR c2.siteid=0) ORDER BY c2.siteid DESC LIMIT 1 );
Ale czy to jest dobre rozwiązanie? Może da się optymalniej?