[英]How do I iterate all rows from two tables connected by foreign key into a single table in PHP, CodeIgniter, MySQL
Say I have Table A and Table B in my SQL database.假设我的 SQL 数据库中有表 A 和表 B。
TABLE A (Users)表 A(用户)
userID![]() |
Name![]() |
Contact![]() |
---|---|---|
userA![]() |
John![]() |
2292 ![]() |
userB![]() |
Dave![]() |
3383 ![]() |
TABLE B (Sports)表 B(运动)
sportID![]() |
Name![]() |
trainer_userID ![]() |
---|---|---|
sportA![]() |
Basketball![]() |
userB![]() |
sportB![]() |
Baseball![]() |
userA![]() |
sportC![]() |
Soccer![]() |
userC![]() |
On my PHP page, I want to combine the two tables, such that the foreign key trainer_userID connects to their respective users.在我的 PHP 页面上,我想组合这两个表,以便外键 trainer_userID 连接到各自的用户。 I can already iterate through each users and show Table A, but can't think of ways to combine both tables such that the output would be:
我已经可以遍历每个用户并显示表 A,但想不出组合两个表的方法,这样 output 将是:
userID![]() |
Name![]() |
Contact![]() |
Sport Handled ID![]() |
Sport Handled![]() |
---|---|---|---|---|
userA![]() |
John![]() |
2292 ![]() |
sportB![]() |
Baseball![]() |
userB![]() |
Dave![]() |
3383 ![]() |
sportA![]() |
BasketBall![]() |
Look up JOINS in SQL.
在 SQL 中查找 JOINS。 This is exactly what relational databases are for.
这正是关系数据库的用途。 Don't implement sql in loop, databases do it better.
不要在循环中实现 sql,数据库做得更好。 Welcome to SO.
欢迎来到 SO。 – danblack 35 mins ago
– danblack 35 分钟前
Solved my problem using the JOINS technique and by using databases instead of looping.使用 JOINS 技术和使用数据库而不是循环解决了我的问题。
SELECT * FROM tableA
INNER JOIN tableB
ON tableA.userID = tableB.trainer_userID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.