2011-05-06 2 views
0

Comment puis-je sélectionner à côté et les lignes précédentes, pour un total de six lignes dans une requête, mais avec des conditions:lignes suivantes et PREVIUS dans une requête MySQL

Je l'ai toujours 6 rangs, donc si j'ai:

1, 2, 3, 4, 5, 6, 7, 8, 9 

et mon ID est 2 le résultat doit être:

1,3,4,5,6,7 

si ma carte d'identité est 5 le résultat doit être:

2,3,4,6,7,8 

si mon ID est 9 le résultat doit être:

3,4,5,6,7,8 

modifier:

(SELECT * FROM articulos 
     WHERE categoria = 'Y' 
     AND numero >= 
     (SELECT IF(
      (SELECT COUNT(*) FROM articulos WHERE numero < X AND categoria = 'Y')<3, 
      (SELECT MIN(X) FROM articulos WHERE categoria = 'Y'), 
      (X-3) 
     )) 
     ORDER by numero ASC LIMIT 6) 
UNION 
(SELECT * FROM articulos 
     WHERE categoria = 'Y' 
     AND numero <= 
     (SELECT IF(
      (SELECT COUNT(*) FROM articulos WHERE numero > 1605 AND categoria = 'Y')<3, 
      (SELECT MAX(X) FROM articulos WHERE categoria = 'Y'), 
      (X+3) 
     )) 
     ORDER by numero DESC LIMIT 6) 

peut-être c'est la solution

Répondre

1

Quelque chose comme ceci:

SELECT data 
FROM table 
JOIN (SELECT 
    CASE 
     WHEN n > MAX(id)-3 THEN MAX(id) - 7 
     WHEN n < 4 THEN 0 
     ELSE n - 4 
    END AS lower_bound, 
    CASE 
     WHEN n > MAX(id)-3 THEN MAX(id) + 1 
     WHEN n < 4 THEN 7 
     ELSE n + 4 
    END AS upper_bound 
    FROM table) AS t1 
WHERE id BETWEEN t1.lower_bound AND t1.upper_bound 
AND id <> n 

devrait toujours sélectionner 6 rangées

Plus d'informations sur le CASE fonction in the docs

Questions connexes