sql >> Base de Datos >  >> RDS >> Mysql

seleccionar solo cuando el valor es diferente

Si desea excluir filas que coincidan con el name anterior , hay varias formas como las siguientes.

Caso 1:si usa MySQL8, puede usar RETRASO función.

SELECT t1.id,t1.name,t1.price FROM (
  SELECT t2.id,t2.name,t2.price,
    LAG(t2.name) OVER(ORDER BY t2.id) prev
  FROM mytable t2
) t1
WHERE t1.prev IS NULL OR t1.name<>t1.prev
ORDER BY 1

Caso 2:Si el id s son continuos sin ningún paso, obtendrá el resultado esperado al comparar name y el anterior id por UNIRSE.

SELECT t1.id,t1.name,t1.price FROM mytable t1
  LEFT JOIN mytable t2
  ON t1.name=t2.name AND
     t1.id=t2.id-1
WHERE t1.id=1 OR t2.id IS NOT NULL
ORDER BY 1

Caso 3:Si el id s no son continuos, hay una manera de obtener el máximo id que no supere al otro id .

SELECT t1.id,t1.name,t1.price FROM mytable t1
  LEFT JOIN mytable t2
  ON t1.name=t2.name AND
     t1.id=(SELECT MAX(t3.id) FROM mytable t3 WHERE t3.id<t2.id)
WHERE t1.id=1 OR t2.id IS NOT NULL
ORDER BY 1

DB Fiddle