mysql将表1中的同一列作为外键引用到表2中的两列

u59ebvdq  于 2021-06-19  发布在  Mysql
关注(0)|答案(4)|浏览(310)

我有两个mysql表,其中第二个表有对第一个表的外键引用。第一个表格如下:
第一个表名:treeview

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

我使用这个表来生成jstree。我的第二张table如下:
第二个表名:注解:

+--------+-------------------------------------+--------------+-----------+
| 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中两列的外键吗?这个箱子怎么取?

lyr7nygr

lyr7nygr1#

那是一次,两次

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

ut6juiuv

ut6juiuv2#

您应该对treeview表使用两个join,一个用于引用表注解的每列

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

kxeu7u2r3#

你必须使用不同的别名 treeview 你用过两次的table。不需要 and 之前 inner join... .
查询

select `t1`.`imagename`, `t2`.`name`, `t3`.`text`
from `annotations` as `t1` 
inner join `treeview` as `t2`
on `t2`.`id` = `t1`.`locationName`
inner join `treeview` as `t3` 
on `t3`.`id` = `t1`.`brandname`;

在此处查找演示

sq1bmfud

sq1bmfud4#

从注解a、treeview t1、treeview t2中选择a.imagename、t1.name、t2.name,其中a.locationname=t1.id&&a.brandname=t2.id;

相关问题