Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Inner Joins MYSQL

Tags:

How would I preform two inner joins in one query?

Ie: three tables

Invoice
Address
Client

Invoice has a column which references an id in clients. It also has a column which references an address. I need to get both the clients name from the matched table and the address from the matched table. How would I INNER JOIN both tables?

I'll add a few details...
invoice has rows address(references address id), client(references client id), id and notes client has rows first_name, last_name address has rows street_name and city

I need to pull up

like image 721
Yoshiyahu Avatar asked Feb 06 '11 23:02

Yoshiyahu


People also ask

Can you use two inner joins?

You can have as many JOIN clauses as you need in the query. Each has an ON clause where you specify the related columns between the joined tables.

How do I add multiple inner joins?

In this case the two tables are joined using the relationship table1.id = table2.id . It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.

How do I write multiple inner join queries in SQL?

$result = mysql_query("SELECT * FROM `table1` INNER JOIN `table2` ON table1. primaryKey=table2. table1Id"); I'd like to extend this to multiple tables (all with the same foreign keys).

How can I join two tables in MySQL?

Ans: Joining two tables in SQL can be done in four major ways: Inner Join (returns rows with matching columns), Left Join (ALL records in the left table and matching records in the right table), Right Join (ALL records in the right table and matching records in the left table), and Union (removes duplicates).


2 Answers

You can have as many JOIN clauses as you need in the query. Each has an ON clause where you specify the related columns between the joined tables.

SELECT   columns FROM   invoice INNER JOIN   address ON   join_condition INNER JOIN   client ON   join_condition 
like image 184
Dan Grossman Avatar answered Sep 22 '22 15:09

Dan Grossman


Something like:

SELECT    c.*, i.*, a.*  FROM    invoices i  INNER JOIN    client c  ON    i.clientid = c.clientid  INNER JOIN    address a  ON    a.clientid = c.clientid  WHERE    i.id = 21 

Don't forget you only select the fields you require, not * (all).

like image 32
Prisoner Avatar answered Sep 22 '22 15:09

Prisoner