Ho seguito, semplice tabellaMySQL set di risultati ordinato da posizioni fisse
Item (id, name, date, fixed_position)
(1, 'first entry', '2016-03-09 09:00:00', NULL)
(2, 'second entry', '2016-03-09 04:00:00', 1)
(3, 'third entry', '2016-03-09 05:00:00', NULL)
(4, 'fourth entry', '2016-03-09 19:00:00', NULL)
(5, 'fifth entry', '2016-03-09 13:00:00', 4)
(6, 'sixth entry', '2016-03-09 21:00:00', 2)
Il numero di elementi non è fisso, infatti può variare da 100 a ~ ~ 1000.
Quello che voglio ottenere è eseguire una query per restituire il set di articoli ordinati per date
campo che prende in considerazione il campo fixed_position
, che corrisponde a qualcosa come risultati "appuntati" a posizioni specifiche. Se fixed_position
per la voce data non è NULL, il risultato deve essere bloccato in n-esima posizione e se fixed_position
è NULL, il ORDER BY
deve avere la precedenza.
output desiderato di query per una spiegazione più luminoso: soluzione
(2, 'second entry', '2016-03-09 04:00:00', 1) // pinned to 1-st position
(6, 'sixth entry', '2016-03-09 21:00:00', 2) // pinned to 2-nd position
(3, 'third entry', '2016-03-09 05:00:00', NULL) // ORDER BY `date`
(5, 'fifth entry', '2016-03-09 13:00:00', 4) // pinned to 4-th position
(1, 'first entry', '2016-03-09 09:00:00', NULL) // ORDER BY `date`
(4, 'fourth entry', '2016-03-09 19:00:00', NULL) // ORDER BY `date`
Ho provato ha scritto in Ordering MySql results when having fixed position for some items, ma anche con il metodo copia-incolla questo non sembra funzionare affatto.
Quello che ho provato fino a questo punto è questa query:
SELECT
@i := @i +1 AS iterator,
t.*,
COALESCE(t.fixed_position, @i) AS positionCalculated
FROM
Item AS t,
(
SELECT
@i := 0
) AS foo
GROUP BY
`id`
ORDER BY
positionCalculated,
`date` DESC
che restituisce:
iterator | id | name | date | fixed_position | positionCalculated
1 1 first entry 2016-03-09 09:00:00 NULL 1
2 2 second entry 2016-03-09 04:00:00 1 1
6 6 sixth entry 2016-03-09 21:00:00 2 2
3 3 third entry 2016-03-09 05:00:00 NULL 3
4 4 fourth entry 2016-03-09 19:00:00 NULL 4
5 5 fifth entry 2016-03-09 13:00:00 4 4
Vuol MySQL in grado di eseguire tale compito o dovrei prendere approccio backend ed eseguire di array_merge()
su due PHP set di risultati?
Qual è la SQL che si sta utilizzando? In modo che possiamo vedere ciò che hai provato. IE: 'order by date, ifnull (fixed_position, 0)' –
Ho aggiunto la query di esempio nella mia domanda. Trascorso più di 5 ore in questa ricerca di una risposta, si è conclusa con quasi nulla. –
È 'fixed_position' un campo nella tabella o un campo calcolato? –