MySQL将表连接到查询中,与其他人没有参考

时间:2017-07-11 16:54:13

标签: mysql join

我想从多个prestashop表中进行查询,以便能够将其导入另一个数据库。问题是第三个表没有对其他两个表的参考,也无法弄清楚如何将它们连接在一起。

为了简化事情,可以说3表格如下:

Table1  Table2           Table3
ID      ID | Table1 ID   ID
------  --------------   ------
1       11 | 1           12
2       22 | 1           13
3       44 | 2           
        55 | 2
        66 | 3
        77 | 3

我想要这个结果:

firstID | secondID | thirdID
1       | 11       | 12
1       | 22       | 12
1       | 11       | 13
1       | 22       | 13
2       | 44       | 12
2       | 55       | 12
2       | 44       | 13
2       | 55       | 13
3       | 66       | 12
3       | 77       | 12
3       | 66       | 13
3       | 77       | 13

或者说,我想为每个Table2 ID分配everery Table3 ID,并且还显示Table2对Table1的引用,也就是Table1 ID

当我查询Table1和Table2时,我通常这样做:

SELECT p.`id` AS `firstID`, pa.`id` AS `secondID`
FROM `Table1` p
LEFT JOIN `Table2` pa ON (p.`id` = pa.`id`)
GROUP BY pa.`id`
ORDER BY p.`id`

但是我无法加入第三张桌子,所以它会产生预期的结果。

如何实现上述结果?

2 个答案:

答案 0 :(得分:1)

您正在寻找cross join inner join。试试:

Select 
a.ID, b.ID, c.ID
from 
Table1 a Inner Join 
Table2 b on a.ID = b.Table1_ID
Cross Join 
Table3 c

这将根据ID获取table1和table2,table3将与result交叉连接。

有关交叉加入的更多信息,请访问here

答案 1 :(得分:0)

编辑:重命名表格ID以匹配OP表格结构。

SELECT t1.`ID` AS `firstID`, t2.`ID` AS `secondID`, t3.`ID` AS `thirdID`
FROM `Table1` t1
LEFT JOIN `Table2` t2 ON (t1.`ID` = t2.`Table1 ID`)
LEFT JOIN `Table3` t3 ON 1
ORDER BY t1.`ID`, t3.`ID`

这会产生与您预期相同的结果。

SELECT t1.`ID` AS `firstID`, t2.`ID` AS `secondID`, t3.`ID` AS `thirdID`
 FROM `Table3` t3, `Table1` t1
 LEFT JOIN `Table2` t2 ON (t1.`ID` = t2.`Table1 ID`)
 ORDER BY t1.`ID`, t3.`ID`