[英]select columns from 2 tables with rows as column having same id
I have 2 tables with various columns and the tokenid being the same for both. 我有2个具有不同列的表,并且tokenid都相同。 The second table has multiple rows with same tokenid and other columns are different.
第二个表具有具有相同标记ID的多个行,而其他列则不同。
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. 现在,我需要从两个表中选择令牌ID相同的列,在第二个表中,必须将具有相同令牌ID的行转换为列。
Table1: 表格1:
tokenid acolumn1 acolumn2 acolumn4
1 fname1 mname1 lname1
2 fname2 mname2 lname2
Table2: 表2:
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. 我尝试首先使用distinct查询第二个表,并将其用作与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. 但是该数据库在表2中有超过200,000行,并且与由
acolumn1
选择的acolumn1
将产生约20000行结果。 So my query doesnt complete. 所以我的查询没有完成。 is there any optimized way to solve this?
有没有优化的方法来解决这个问题?
PS: I'd like to add that I do the queries with php using pdo PS:我想补充一点,我使用pdo用php进行查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.