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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.