MySQL-连接两个表,表1中的不同列位于表2中的同一列上
我正试图将MySQL-连接两个表,表1中的不同列位于表2中的同一列上,mysql,join,Mysql,Join,我正试图将Table1上的另一列(part\u type\u n(其中n的范围为1到54))与Table2上的同一列(id,primary,autoinc)连接起来 模式: Table1 ============== part_type_1 . . . part_type_54 Table2 ============= id 表1 ============== 零件类型1 . . . 零件类型54 表2 ============= 身份证件 我尝试了一个明显的查询(php生成,从1到54循
Table1
上的另一列(part\u type\u n
(其中n的范围为1到54))与Table2
上的同一列(id
,primary,autoinc)连接起来
模式:
Table1
==============
part_type_1
.
.
.
part_type_54
Table2
=============
id
表1
==============
零件类型1
.
.
.
零件类型54
表2
=============
身份证件
我尝试了一个明显的查询(php生成,从1到54循环n),省略了…中重复的内容:
SELECT*FROM Table1 JOIN Table2 on(Table1.part\u type\u 1=Table2.id),…,(Table1.part\u type\u 54=Table2.id)
我收到这个错误:
1066-非唯一表/别名:“Table2”
如何连接这两个表?您必须多次自行连接表
SELECT * FROM table1 t1
INNER JOIN table2 t2 on t2.Id=t1.part_type_1
INNER JOIN table2 t3 on t3.id = t1.part_type_54;
希望这有帮助 > P>作为用54个表别名编写查询的替代方案,您可以考虑加入到表中一次-如:
select ...
from Table1 t1
join Table2 t2
on t2.id in (t1.part_type_1, t1.part_type_2, ... t1.part_type_54)
对于我来说,获得所需的结果非常有效,因为其中一行匹配所有存储在一个表列中的各种类别 查询
SELECT cm3.*, xp.post_title,GROUP_CONCAT(DISTINCT sc.name) AS cate_list
FROM `xld_posts` xp
JOIN course_map cm0 ON cm0.course_id = xp.ID
JOIN course_map cm1 ON cm1.course_id = cm0.course_id AND cm0.id = 3
JOIN course_map cm2 ON cm2.course_id = cm1.course_id AND cm1.id = 6
JOIN course_map cm3 ON cm3.course_id = cm2.course_id AND cm2.id = 11
JOIN subject_category sc ON cm3.id = sc.id
GROUP by post_title ORDER BY post_title
注:类别值3、6和7来自表单sumbit。因此,如果您的表单有三个或三个以下的表,您的查询应该动态创建,并将每个表与前一个表连接起来
:)如果有人觉得有用,那就高兴。为什么内部联接和非联接联接是内部联接的简写-有没有理由不使用简写在性能和实现上绝对没有区别。我个人更喜欢编写内部连接,因为它更易于阅读。在这种情况下,只使用54个单独的调用而不是单个调用会更好吗?您真的想只从表1中选择那些表2记录与所有54个part_类型值匹配的记录吗?