Page is a not externally linkable
- Code, Content, and Presentation
-- Databases
---- Joining 3 tables


rocknbil - 5:55 pm on Aug 31, 2010 (gmt 0)


Welcome aboard tejayuu, a couple things. first, you are missing a )

SELECT t1.* , t2.name AS repliername, t3.centre_name
FROM ((tickets AS t1 LEFT JOIN users AS t2 ON t1.replierid = t2.id)
LEFT JOIN centres as t3 ON t3.id = t1.name )

which shouldn't be necessary anyway.

SELECT t1.* , t2.name AS repliername, t3.centre_name
FROM tickets AS t1 LEFT JOIN users AS t2 ON t1.replierid = t2.id
LEFT JOIN centres as t3 ON t3.id = t1.name

Second, I have never done "table as [placeholder]," I think those only apply to selected fields. Try


SELECT tickets.* , users.name AS repliername, centers.centre_name
FROM tickets LEFT JOIN users ON tickets.replierid = users.id
LEFT JOIN centres ON centres.id = tickets.name

A thing to be aware of, left joins will return rows even if no matching fields are found for the joined tables. For example, if there's no matching record in centres,

ticketfield1|ticketfield2|repliername|NULL

If you want to display only rows with matching records in all three, this is a bit more legible and will do that.

select tickets.*, users.name as repliername, centers.centre_name
from tickets,users,centres
where tickets.replierid = users.id
and tickets.name = centres.id

If there are records in all three, the results *should* be the same.


Thread source:: http://www.webmasterworld.com/databases_sql_mysql/4194660.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com