Search code examples
sqlmysql

How it works a mysql query with alias?


I'm new in this comunnity and I need to work with a query that get data from a mysql database, I have this query, but I need to add a new table and I don't understand why the query has a alias, I don't know how it works, someone can help me? This is my query:

SELECT ins.matricula, pe.nombres, pe.appaterno, pe.apmaterno, co.calleynum, co.colonia, co.municipio, co.telfijo, co.telcelular, pe.fechanac, pe.sexo, co.email, pe.institucion, tu.tnombres, tu.tappaterno, tu.tapmaterno, tu.direccion, tu.telefono, ins.fechains, ins.niveledu, ins.fechaini, ins.horario 
FROM Inscripciones ins 
LEFT JOIN Perfiles pe 
       ON pe.idperfil=ins.idperfil 
LEFT JOIN Contactos co 
       ON co.idperfil = pe.idperfil 
LEFT JOIN Tutores tu 
       ON tu.matricula = ins.matricula 
WHERE pe.idperfil='$var'

I have read the mysql docs but I can't understand how it works.


Solution

  • In MySQL, an "alias" can be declared to simplify the query later. Typically this is denoted with the "AS" operator, but can also be declared without "AS" - as in your example.

    In your example:

    SELECT ins.matricula, {...}
    FROM Inscripciones ins {...}
    

    The ins is set as an alias for the "Inscripciones" table. This allows you to use ins throughout the query rather than typing out "Inscripciones." This can be seen in the SELECT statement. Something to keep in mind - aliases in SQL can be declared after they're first used. This is the case in your example, where SELECT gets ins.matricula before you've actually declared ins as the alias for Inscripciones. Sometimes this seems counter intuitive, but I promise it will make sense if you experiment with it a bit.

    I find it less ambiguous to include the "AS" - which might help it make more sense as you're reading/writing the SQL query. ex: ... FROM Inscripciones AS ins

    To be clear, the use of the alias doesn't change the outcome of your query, but helps you write cleaner queries because you don't have to re-write the tablename every time you want to use it.