Search code examples
phphtmlmysqlphpmyadminrdbms

How to join two tables in PHP - MySQL that match an ID in the second table and still display specific record in table 1?


I have two tables (account and restaurant) How can I display all records from two tables but exclude some records?

table: account
+-------+----------+------------+
| uid   | name     | role       |
+-------+----------+------------+
|  1    | John     | Admin      |
|  2    | Steve    | Resto_Owner|
|  3    | Bill     | Customer   |
+-------+----------+------------+

table: restaurant
+--------+----------+------------+
|resto_id|  uid     | resto_name |
+--------+----------+------------+
|  1     |   2      |Steve Resto |
+--------+----------+------------+


**This is my Desired Output:** 
+-------+----------+------------+--------------+
| uid   | name     | role       | resto_name   |
+-------+----------+------------+--------------+
|  1    | John     | Admin      |              |
|  2    | Steve    | Resto_Owner| Steve Resto  |
+-------+----------+------------+--------------+

I want to display records from these two tables with the role admin and resto_owner. But also display the resto_name if the role is resto_owner, blank if admin and do not display if customer

I tried to use INNER JOIN but it only display: 2 Steve Resto_Owner Steve Resto and does NOT display the admin record:

Thank you in advance :)


Solution

  • Use left join with conditions

     SELECT account_table.uid, account_table.name, account_table.role, restaurant_table.resto_name 
        FROM account account_table LEFT JOIN restaurant restaurant_table
        ON restaurant_table.uid = account_table.uid 
        WHERE account_table.role <> 'Customer' ORDER BY account_table.uid ASC
    

    More in https://www.w3schools.com/sql/sql_join_left.asp