简体   繁体   English

如何将通过外键连接的两个表中的所有行迭代到 PHP、CodeIgniter、MySQL 中的单个表中

[英]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用户A John约翰 2292 2292
userB用户B Dave戴夫 3383 3383

TABLE B (Sports)表 B(运动)

sportID运动ID Name姓名 trainer_userID trainer_userID
sportA运动A Basketball篮球 userB用户B
sportB运动B Baseball棒球 userA用户A
sportC运动C Soccer足球 userC用户C

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运动处理 ID Sport Handled运动手柄
userA用户A John约翰 2292 2292 sportB运动B Baseball棒球
userB用户B Dave戴夫 3383 3383 sportA运动A 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.

相关问题 如何从两个表中查询匹配表中的外键和另一个表中的主键 - How do I query from two tables matching the foreign key from table with the primary key from another MYSQL SELECT使用或不使用外键从两个表中获取行 - MYSQL SELECT To fetch rows from two tables with or without a foreign key 如何从 mysql 表中获取所有行,发送 json,遍历数组并显示? - How do I get all the rows from a mysql table, send json, iterate through array and display? 如何通过外键从两个不同的表中获取所有字段 - How to get all fields from two different tables by foreign key 如何使用MySQL PHP将两个表中的数据插入到一个表中 - How do I Insert data from two tables into one table using MySQL PHP 如何将主键放入另一个表的外键中? PHP,MySQL - How Do I Grab And Put Primary Key Into Foreign Key In Another Table? PHP, MySQL 如何从由第三个表连接的两个mySQL表中选择数据? - How can I select data from two mySQL tables connected by a third table? 如何在mySQL和PHP中的两个表中添加数据? - How do I add data from two tables in mySQL and PHP? 在PHP的单行上显示来自不同表(与外键相关)的两个字段中的数据 - Display data from two fields from different tables (related by a Foreign Key) on a single row in PHP 如何从mysql将行检索到php / html表中 - How do I retrieve rows from mysql into a php/html table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM