Reputation: 51
I would still classify myself as a beginner in PHP and mysqli databases and I could use some help. I have looked around on the site and I could not find a clear answer.
I currently have a table of 150 athletes which each have been assigned an Auto Incremented ID (column one 'athlete_id')and some stats for each athlete in additional columns which have been set up like such: MySQL 'athletes' table
Next, I have another table within the same database named 'selection'(image here) in the selection table there is an id column which gathers the logged in users id from my session and places the users_id into column 1 of id in 'selection'. The remaining columns are the id's of athletes (athlete_id) in which the logged in user has selected and have been inserted into the table. Id's of athlete1, athlete2 etc. correspond to the athlete_id in "athletes" (table 1)
What I am attempting to do is perhaps select the users_id from the session (which I have done and for this example I use '21' as 'user_id' in session) then grab the athletes_id the user has selected that are in the 'selection' table under columns athlete1 athlete 2 etc. then replace the athlete id with real name and statistics which are in the 'athletes table'
Below I have joined the tables but under this way it only shows athlete3 that user 21 selected and I am unsure of how to show all selections of user 21 in an effective way. How would i be able to show all athletes selected from user 21?
SELECT * FROM athletes LEFT JOIN selection ON athletes.athlete_id=selection.athlete3 WHERE id=21
In the future, I will be using this info to show the selected athletes along with the athletes stats to the logged in user via an HTML table on a website. I have made this example to show my end goal for this.
The way I have gone about storing each athlete selection in separate columns (athlete1, athlete2, athlete3) may be EXTREMELY inefficient in my case and if there is another much simpler way to achieve the same result I would very much appreciate the tip and I could change my entire approach to this problem.
I have considered storing the selected athlete_id in one column with commas ex: 4,8,9 but im unsure how to do this so if that is an easier solution I could use some help from someone more experienced.
Upvotes: 0
Views: 903
Reputation: 138
I will try to solve your problem. If you want to do a join query you must have the same column as the other table columns.
As in your case, you must have 1 column in the selection
table which is the same as the athletes
table's athlete_id
. So the query that you will generate.
SELECT * FROM athletes
LEFT JOIN selection ON athletes.athlete_id = selection.athlete_id
WHERE selection.id = 21;
Hopefully, this can solve your problem.
Upvotes: 1