首页 > 解决方案 > Mysql将表1中的同一列作为外键引用到表2中的两列

问题描述

我有两个 mysql 表,第二个表具有对第一个表的外键引用。第一张表如下:

第一个表名称:树视图

+----+-----------+-----------+-----------+
| id | name      | text      | parent_id |
+----+-----------+-----------+-----------+
|  1 | BrandTree | BrandTree | 0         |
|  2 | TShirt    | TShirt    | 1         |
|  3 | ManForce  | ManForce  | 2         |
|  4 | PayTM     | PayTM     | 2         |
+----+-----------+-----------+-----------+

我正在使用这个表来生成一个 jstree。我的第二张表如下:

第二个表名:注释:

+--------+-------------------------------------+--------------+-----------+
| ann_id | imagename                           | locationName | brandname |
+--------+-------------------------------------+--------------+-----------+
|      1 | 95-20180527-190018-205342-00002.jpg |            2 |         3 |
|      2 | 95-20180527-190018-205342-00005.jpg |            2 |         4 |
+--------+-------------------------------------+--------------+-----------+

在第二个表中,locationName 和 brandname 具有对第一个表 id 列的外键引用。我正在使用以下代码来检索表:

select annotations.imagename, treeview.name, treeview.text 
from annotations 
inner join treeview on treeview.id = annotations.locationName 
and inner join treeview on treeview.id = annotations.brandname;

上面的代码提供了一个空集。

我可以将表 1 中的 id 列作为表 2 中两列的外键吗?在这种情况下我该如何获取?

标签: mysqlforeign-keys

解决方案


那就是一次加入,两次

select annotations.imagename, tv1.name, tv2.name 
from annotations 
inner join treeview tv1 on tv1.id = annotations.locationName 
inner join treeview tv2 on tv2.id = annotations.brandname;

我想,没有方便的mysql


推荐阅读