Jump to content

Join 3 tables (newbie)


Segbarn

Recommended Posts

Hello I am very new to MySQL and PHP but I think I am mature enough to be able to post here.

I have 3 tables where I want to list all rows of the table "nuke_demands".
I want to have the 8 columns username,from_servername,from_servercountry,from_servertype,to_servername,to_servercountry,to_servertype,amount so that I can use "ORDER BY" statement properly.
I dont understand how to handle a join when there are 3 tables involved. If I divide the queries in two I cannot do the ORDER thing right? Can you please give me a hint?

username is in nuke_users and should be getable through the user_id.
the serverinfo should be some kind of join of nuke_servers and nuke_demands.
amount is just picked from nuke_demands directly.

table: nuke_users
user_id username

table: nuke_servers
id servername country type

table: nuke_demands
user_id from_server to_server amount
[i]from_server and to_server are the ids of servers[/i]


This is what I tried:
[code]sql_test3 = "SELECT username,from_servername,from_servercountry,from_servertype,to_servername,to_servercountry,to_servertype,amount FROM nuke_users,nuke_servers WHERE username in (SELECT nuke_users.username FROM nuke_demands,nuke_users
WHERE (nuke_demands.user_id=nuke_users.user_id)) AND (from_servername,from_servercountry,from_servertype) in (SELECT nuke_servers.servername,nuke_servers.country,nuke_servers.type FROM nuke_demands,nuke_servers WHERE nuke_demands.from_server_id=nuke_servers.id) AND (to_servername,to_servercountry,to_servertype) in (SELECT nuke_servers.servername,nuke_servers.country,nuke_servers.type FROM nuke_demands,nuke_servers WHERE nuke_demands.to_server_id=nuke_servers.id) AND amount in (SELECT amount FROM nuke_demands)";[/code]
Link to comment
https://forums.phpfreaks.com/topic/34031-join-3-tables-newbie/
Share on other sites

try

[code]
SELECT u.username, d.amount,
        sf.servername as from_servername, sf.country as from_servercountry, sf.type as from_servertype,
        st.servername as to_servername, st.country as to_servercountry, st.type as to_servertype
FROM nuke_users u
        INNER JOIN nuke_demands d ON u.user_id = d.user_id
        INNER JOIN nuke_servers sf ON sf.id = d.from_server
        INNER JOIN nuke_servers st ON st.id = d.to_server
ORDER BY u.username, sf.servername, st.servername
[/code]

Note the join to nuke_servers twice - to pick up name,country,type for the from_server and again for the to_server
Link to comment
https://forums.phpfreaks.com/topic/34031-join-3-tables-newbie/#findComment-160176
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.