views:

39

answers:

3

I have four tables:

  • characters
  • arena_team
  • arena_table_member
  • arena_team_stats.

characters table has guid, name

arena_team table has arenateamid, name, type

arena_table_member table has guid(this is the same as in characters table), arenateamid

arena_team_stats table has arenateamid, rating, wins, wins2, played

How do I get the list of arena teams where character is? I tried:

$result=mysql_query("SELECT 
          characters.guid
           , characters.name
           , arena_team.arenateamid
           , arena_team.name
           , arena_team_stats.rating
           , arena_team_stats.wins
           , arena_team_stats.wins2
           , arena_team_stats.played
           , arena_team.type 
   FROM characters
           , arena_team_stats
           , arena_team 
    WHERE characters.name LIKE '%$q%' 
    AND arena_team.arenateamid = arena_team_stats.arenateamid 
    ORDER BY arena_team_stats.rating DESC") 
or die(mysql_error());

but it returns all arena teams which are in arena_team table.

+3  A: 

You should use Joins instead. When you use comma separated table in the FROM part, you get all possible combinations in the result.

Try this query (using Joins):

SELECT c.guid,c.name,a.arenateamid,a.name,
  ts.rating,ts.wins,ts.wins2,
  ts.played,a.type 
 FROM characters c
         JOIN arena_table_member ON arena_table_member.guid=character.guid
  JOIN arena_team a ON arena_table_member.arenateamid = a.arenateamid
  JOIN arena_team_stats ts ON ts.arenateamid = a.arenateamid
 WHERE c.name LIKE '%$q%' 
  AND a.arenateamid = ts.arenateamid 
 ORDER BY ts.rating DESC

Two things:

  1. You should use aliases here. (The c, a, ts above instead of full table names are called aliases)

  2. If you want to match exactly with character '?', use c.name = '?'. c.name like '%?%' will return all c.names which have a ? in them.

Raze2dust
+1  A: 

Looks like you're missing a JOIN. It's easier to read with table aliases and formatted:

    SELECT c.guid
         , c.name
         , at.arenateamid
         , at.name
         , at.type
         , ats.rating
         , ats.wins
         , ats.wins2 
         , ats.played
      FROM characters c
INNER JOIN arena_team_member atm ON atm.guid = c.guid
INNER JOIN arena_team at ON at.arenateamid = atm.arenateamid
INNER JOIN arena_team_stats ats ON ats.arenateamid = at.arenateamid
     WHERE c.name LIKE '%$q%'
  ORDER BY ats.rating DESC
AvatarKava
A: 
SELECT Char.guid, Chars.name, Teams.arenateamid, Teams.name, Stats.rating,
       Stats.wins, Stats.wins2, Stats.played, Teams.type
FROM characters AS Chars,arena_team_stats AS Stats, arena_team AS Teams,
     arena_table_member AS Members
WHERE Chars.name LIKE '%$q%' AND Teams.arenateamid = Stats.arenateamid AND
      Members.guid = Chars.guid AND Members.arenateamid = Teams.arenateamid
ORDER BY Stats.rating DESC

You were missing some table joins.

vtorhonen