我正在编写SQL语句,并且在加入两个表时我们遇到问题(我们称之为表注册&产品)在表格注册的列StudentID的外键列上。 StudentID是从变量$ StudentID中读取的。选择加入表A和表B,同时根据表A的外键显示表B项目
报名表
+--------------+-----------+-----------+
| EnrollmentID | StudentID | ProductID |
+--------------+-----------+-----------+
| 1 | 5 | 1 |
| 2 | 5 | 2 |
|3 | 7 | 2 |
|4 | 7 | 3 |
|5 | 9 | 5 |
+--------------+-----------+-----------+
产品表
+-----------+-------------+------------+
| ProductID | ProductName | ProductDate|
+-----------+-------------+------------+
|1 | ProductA | 1/1/2017 |
|2 | ProductB | 1/2/2017 |
|3 | ProductC | 1/3/2017 |
|4 | ProductD | 1/4/2017 |
+-----------+-------------+------------+
这是SQL语句到目前为止,我已经出来,并有麻烦:
"SELECT product.ProductName, product.ProductDate
FROM enrollment WHERE StudentID = '$StudentID'
RIGHT JOIN product ON enrollment.productid = product.productid";
如果$ StudentID是5.我希望它显示与StudentID 5关联的ProductID中的所有项目。在这种情况下,Product A和Pr输出B将是输出。
听起来好像'Enrollment'是[**桥接表**](https://en.wikipedia.org/wiki/Associative_entity),以及'StudentID'被来自**第三张桌子(“学生”)。您还需要加入该表格:) –
是的,它来自第三个表格。但是该表中没有使用列,而只使用了“StudentID”。我不熟悉加入三张表。 –
如果你不显示第三张表中的数据,那么你仍然**使用** ID将这两张表“关联”在一起。要将三个表连接在一起,您基本上只需要在末尾(在“注册”和“学生”之间)添加另一个“JOIN”。这里是[**一些例子**](https://stackoverflow.com/questions/3709560/mysql-join-three-tables)来帮助那个:) –