Query to get all records regardless of whether they exist in another table or not

Asked

Viewed 38 times

1

I’m running an app from a store where users can leave equipment to be fixed. So I made a php to search by name those users who have already left some equipment:

        $sql = mysqli_query("$conexao,
        SELECT u.contribuinte, u.nome, u.tlm
        FROM utilizador u, entrada e
        WHERE u.contribuinte = e.contribuinte
        AND u.nome LIKE  '%".$utilizador."%'
        ORDER BY e.data_entrada DESC 
        "); 

However in query above I can get these results, but also wanted to get users regardless whether they have left any equipment or not. In other words, I want all users to appear, taking as a priority those who have already left some equipment.

This is the first time I have seen such a case, but I think it is possible to perform this query. I thank you already for the help :)

1 answer

1


Use LEFT JOIN for this.

SELECT u.contribuinte, u.nome, u.tlm
FROM utilizador AS u
LEFT JOIN entrada AS e ON u.contribuinte = e.contribuinte
WHERE u.nome LIKE  '%".$utilizador."%'
ORDER BY e.data_entrada DESC 
  • Thanks Givanildo! had never used nor had heard about that keyword.

  • Blz @programmer2016. When you can, do a little research on: types of Joins. Up to +

Browser other questions tagged

You are not signed in. Login or sign up in order to post.