Jump to content

Query from 3 tables?


Tandem

Recommended Posts

Hey there,

I'm currently runnung a text based game. Within the game are players can come together to create gangs. I have a leader board page which displays a league table for which gang has the most money.

Here's the query that it uses:

[code]<?php
$gangs = mysql_query("SELECT m.GANG,
CASE WHEN SUM(b.DEPOSIT) IS NULL
THEN SUM(m.CASH)
ELSE (
SUM(m.CASH) + SUM(b.DEPOSIT)
)
END AS total
FROM USERS m
LEFT JOIN BANK b ON m.USERNAME = b.USERNAME WHERE m.LIFESTATUS='Alive' AND m.GANG!='None' AND m.GANG!='The Staff'
GROUP BY m.GANG ORDER BY total DESC, m.CASH DESC");
?>[/code]

It adds up each gang members cash, and includes the cash in thier "bank account" if they have one.

This works fine. But now i need to add a figure from a third table in there. How should i go about this?

Please ask for more info if you need it.

Thanks.
Link to comment
https://forums.phpfreaks.com/topic/28190-query-from-3-tables/
Share on other sites

SELECT m.GANG,
CASE WHEN SUM(b.DEPOSIT) IS NULL
THEN SUM(m.CASH)
ELSE (
SUM(m.CASH) + SUM(b.DEPOSIT)
)
END AS total
FROM USERS m
LEFT JOIN BANK b ON m.USERNAME = b.USERNAME
LEFT JOIN table3 t3 ON tX.field = t3.field
WHERE m.LIFESTATUS='Alive' AND m.GANG!='None' AND m.GANG!='The Staff'
GROUP BY m.GANG ORDER BY total DESC, m.CASH DESC

I'm assuming that you want another left join.  You may very well want a cross or inner join instead depending on your needs.
Link to comment
https://forums.phpfreaks.com/topic/28190-query-from-3-tables/#findComment-128924
Share on other sites

It stands for whatever alias you gave another of your tables in the SQL statement; in this case it'd be either m or b.  I have no idea how you're matching the data in the third table with whats in the other two, so I don't know which table or field to use.
Link to comment
https://forums.phpfreaks.com/topic/28190-query-from-3-tables/#findComment-128938
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.