Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/MYSQL Join multiple tables

Tags:

mysql

Fields from table TICKETS:

ID TICKETID CUSTOMER
234   29      9798797
235   76      7887878

Fields from table RECEPTS:

ID   DATENEW    TOTAL
234 2012-12-03   22.57
235 2012-12-03   33.98

Fields from table PAYMENTS:

RECEIPT   PAYMENT
234       cash
235       debt

Fields from table CUSTOMERS:

ID            NAME
9798797       John
7887878       Helen

The relation between tables is very easy to understand: TICKETS.CUSTOMER=CUSTOMERS.ID; PAYMENTS.RECEIPT=RECEIPTS.ID=TICKETS.ID

The Final Result I would like to achive to have:

TICKETID DATENEW      NAME    PAYMENT TOTAL
29       2012-12-03   John     cash   22.57
76       2012-12-03   Helen    debt   33.98

I tried to do something like this but it wrong somewhere:

Select TICKETS.TICKETID, RECEIPTS.DATENEW, PAYMENTS.TOTAL,  CUSTOMERS.NAME, PAYMENTS.PAYMENT FROM PEOPLE, RECEIPTS 
INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
ORDER BY RECEIPTS.DATENEW
like image 532
Sergiu Costas Avatar asked Dec 03 '12 13:12

Sergiu Costas


People also ask

How can I join more than two tables in PHP?

If you want to load data from multiple table then at that time you can use inner join keyword and merge two table or more table with common column between two or more table. Here I have use two table brand and product. Brand table has two column brand_id and brand_name, brand_id is a primary key.

Can you join multiple tables in MySQL?

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.

Can we join more than 3 tables?

Using JOIN in SQL doesn't mean you can only join two tables. You can join 3, 4, or even more! The possibilities are limitless.

Can we use join for more than 2 tables?

If you'd like to combine data stored in multiple (more than two) tables, you should use the JOIN operator multiple times. First, you join two tables as you normally would (using JOIN , LEFT JOIN , RIGHT JOIN , or FULL JOIN , as appropriate).


1 Answers

You should be able to use the following to get the result:

select t.ticketid,
  date_format(r.datenew, '%Y-%m-%d') datenew,
  c.name,
  p.payment,
  r.total
from tickets t
left join RECEPTS r
  on t.id = r.id
left join CUSTOMERS c
  on t.customer = c.id
left join payments p 
  on t.id = p.RECEIPT
  and r.id = p.RECEIPT

See SQL Fiddle with Demo

Result:

| TICKETID |    DATENEW |  NAME | PAYMENT | TOTAL |
---------------------------------------------------
|       29 | 2012-12-03 |  John |    cash | 22.57 |
|       76 | 2012-12-03 | Helen |    debt | 33.98 |
like image 103
Taryn Avatar answered Nov 15 '22 19:11

Taryn