I’m a student in web developing and I’ve encountered a problem with a MySQL statement. I was asked by a game community to create some sort of little website where they could see which people they banned.
There are 2 tables which I use, ‘accounts’ and ‘bans’. The layout of accounts is somewhat like this
account_id username (more columns)
---- ---- ----
1 hey ...
2 hdf ...
3 sdf ...
4 admin ...
The layout of ‘bans’ is:
ban_id account_id bannedby_id (more columns)
---- ---- ---- ----
1 1 4 ...
2 3 4 ...
In this case an admin with ID 4 has banned the accounts with ID 1 and 3. I want to create a query where I have both the name of the banned person, and the name of the admin who banned him in a single result.
I do this now by first doing:
SELECT bans.*, accounts.username FROM bans, accounts WHERE accounts.account_id = bans.account_id
Then looping over all results and selecting the admin name from the result i got:
while($baninfo = mysql_fetch_assoc($sqlBans))
{
mysql_query("SELECT username FROM accounts WHERE account_id = '" . $baninfo['bannedby_id'] . "'");
}
This worked, but I don’t think this is the correct way to do it. I think there must be a MySQL function which could do such a query but I have searched on Google for it and I couldn’t find it.
Just to be clear, here’s how I would like to get the result from the query:
ban_id account_id account_username bannedby_id admin_username (other columns from Bans table)
---- ---- ---- ---- ---- ----
1 1 hey 4 admin ...
2 3 sdf 4 admin ...
I’m sorry if this is a very stupid question but I could solve it. I hope you guys have a solution for me. Im using this website a lot as I encounter small problems and it always have great answers.
Regards,
Mark
1 Answer