Identify the field in a consula inner join mysql

-1

The following code executes an INNER JOIN query

select * from reservation 
INNER JOIN pacient ON pacient.id_history LIKE '%2%' 
GROUP BY pacient_id 
ORDER BY pacient_id DESC limit 0,12

It turns out that when consulting the id there is a slight shock, there will be some way to solve that

    
asked by Josbert Hernandez Riera 09.07.2017 в 23:21
source

1 answer

2

When there are shocks as you say, it is best to qualify the tables and assign aliases. It is recommended to always qualify the fields and not use the wildcard *, for several reasons, the queries will be more efficient, because we will only call the fields that we need and the engine will not have to look for which fields the table has. The queries will also be more readable, because seeing the query we will know which fields will be returned to us.

Let's go to the mess.

This query

select * from reservation 
INNER JOIN pacient ON pacient.id_history LIKE '%2%' 
GROUP BY pacient_id 
ORDER BY pacient_id DESC limit 0,12

could be left as follows

SELECT 
    reservation.id reservation_id, 
    reservation.otro_campo, 

    pacient.id pacient_id, 
    pacient.otro_campo_pacient
FROM reservation 
INNER JOIN pacient ON pacient.id_history LIKE '%2%' 
GROUP BY pacient_id 
ORDER BY pacient_id DESC limit 0,12

Likewise, making a LIKE in the INNER JOIN does not seem to me the most appropriate. The normal thing is to use an equality something like this:

SELECT 
    reservation.id reservation_id, 
    reservation.otro_campo, 

    pacient.id pacient_id, 
    pacient.otro_campo_pacient

FROM reservation 
INNER JOIN pacient ON reservation.pacient_id = pacient.id
GROUP BY pacient_id 
ORDER BY pacient_id DESC limit 0,12
    
answered by 10.07.2017 в 09:02