I have 2 tables with various columns and the tokenid being the same for both. The second table has multiple rows with same tokenid and other columns are different.
Now, I need to select columns from both table where the token id is the same and in the second table, rows with same tokenid must be converted into columns.
Table1:
tokenid acolumn1 acolumn2 acolumn4
1 fname1 mname1 lname1
2 fname2 mname2 lname2
Table2:
id tokenid bquestion banswer
1 1 questiona answera
2 1 questionb answerb
3 2 questiona answera
4 2 questionb answerb
5 3 questionc answerc
The result should be
tokenid acolumn1 acolumn2 acolumn3 bquestion1 banswer1 bquestion2 banswer2 bquestion3 banswer3
1 fname1 mname1 lname1 questiona answera questionb answerb null null
2 fname2 mname2 lname2 questiona answera questionb answerb questionc answerc
I tried querying the second table first with distinct and used it as a subquery to join with the table1. But the database has more than 200,000 rows in table 2 and the match with a tokenid with selection by acolumn1
will produce about 20000 rows result. So my query doesnt complete. is there any optimized way to solve this?
P.S: I'd like to add that I do the queries with php using pdo