简体   繁体   中英

Query with multiple joins and too many results returned

I am new to php and mysql and I am trying for 2 day to create a web application which can store specific data about the user from the form and than allow users to search based on similar slightly complicated form. I got the forms working and also input to the database but I have the problem with receiving the data from mysql and maybe in the future I will have with the search function too but i did not think much about that yet. Right now I am focusing on getting that specific data from db.

SELECT players.*, 
    brackets.name AS interested_in, 
    classes.name AS looking_for,
    tags.name AS tagged_with 
FROM players JOIN player_brackets ON (players.id = player_brackets.player_id) 
JOIN brackets ON (player_brackets.bracket_id = brackets.id) 
JOIN player_classes ON (player_brackets.player_id = player_classes.player_id) 
JOIN classes ON (player_classes.class_id = classes.id) 
JOIN player_tags ON (player_classes.player_id = player_tags.player_id) 
JOIN tags ON (player_tags.tag_id = tags.id) 
WHERE players.id = '18'

I have this query which works fine but the data i get from it is every combination of the data in the db which is right now about more than 100 results which are all almost the same. Its multiplying the results by number of fields in the db for example players (1) * brackets (3) * classes (11) * tags (5) which will output 165 rows of almost the same data with the difference in fields brackets, classes and tags.

If I group that results by players.id I get just one row but the data from other fields are lost. I want to get 1 row which will contains all of it (col with multiple data in in an array probably).

DB got 7 tables - players, tags, classes, brackets and 3 tables which contains player id and tag/class/bracket id combination.

I have been searching web and SO but nothing really helped me. It would be very nice if someone can help me with this one. Thanks for reply and I am sorry for my poor english its not my primary language.

When you join, MySQL is going to give you every combination.

As you've seen, you can GROUP BY, but then it will only give you one combination.

I think you're looking for a series of queries ("get all brackets for player 1" then "get all classes for player 1 in bracket 12", etc).

Or you can parse the results intelligently in your app.

There's also GROUP_CONCAT, but that rarely meets anyone's needs (since it comes back as one string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM