是否可以在同一个 table 上进行多个连接?

Are multiple joins on the same table possible?

我对从具有多个连接的 table 获取数据有疑问。 Table 1 包含信息(名称和金额),table 2 包含组合。 table 2 中的一行包含与 table 1.

中的 ID 相对应的 ID

我尝试根据 table 2 中的相应 ID 从 table 1 中获取信息。

Table1

Id | Name   | Amount
--------------------
 4 | Test 1 |     50
 5 | Test 2 |     60
 6 | Test 3 |     70
 7 | Test 4 |     80

Table2

id | PriceId | MaterialId | ServiceId
-------------------------------------
 1 |       4 |          5 |         6
 2 |       4 |          5 |         7

查询

了解我试图达到的目标:

SELECT * FROM Table1 a 
LEFT JOIN Table2 b ON a.Id = b.PriceId
LEFT JOIN Table2 c ON a.Id = c.MaterialId
LEFT JOIN Table2 d ON a.Id = d.ServiceId
GROUP BY a.Id

所以我尝试从 table 1 中获取与 table 2 中的 ID 对应的名称和数量,因此:

当我 select Table 2 和 ID 1 中的所有内容时,我尝试获取以下内容:

Table 2 with ID 1: PriceId = 4, MaterialId = 6, ServiceId = 6
Table 1: Test 1, Test 2, Test 3

因为PriceId 4对应Test 1,MaterialID 6对应Test 2等等

希望上面说的很清楚。感谢您的帮助!

看来你是从错误的方向接近它的。你真正想要的是:

SELECT t2.PriceId AS PriceId, 
    t2.ServiceId AS ServiceId, t1p.Name AS PriceName, 
    t1m.Name AS MaterialName, t1s.Name AS ServiceName
FROM Table2 t2
LEFT JOIN Table1 t1p ON t2.PriceId = t1p.Id
LEFT JOIN Table1 t1m ON t2.MaterialId = t1m.Id
LEFT JOIN Table1 t1s ON t2.ServiceId = t1s.Id

是的,你可以用那种方式...... 看我的例子:

select * from movies 
 inner join relationship as r1 on movies.id=r1.movie_id 
inner join relationship as r2 on movies.id=r2.movie_id 
where r1.Taxonomy_id ="xyz" 
and r2.Taxonomy_id="abc"
 GROUP BY movies.id

这对你有用。我在我的一个项目中做到了这一点