我如何获取两个没有外键关系的表的记录?

huangapple go评论59阅读模式
英文:

How I get the record of two table which don't have foreign key relationship?

问题

抱歉,我不能提供代码的翻译。

英文:

Hi Anyone can help me to solve this problem

I have 3 tables FundsPlanning , GradeMst and SupplierMst

I want column SupplierId, WeightLoaded, DeliveryDate, InvoiceAmount, GradeName
like this way.

But the problem is there is no relationship between FundsPlanning and GradeMst.

So the GradeName column exists in GradeMst table.

There is also one table PurchaseContract which has a foreignkey relationship with
SupplierId and GradeId so I can find the Id of Grade.

Using below query I can get the record of Grade column

SELECT GradeId, Grade 
FROM GradeMst 
WHERE GradeId In (SELECT Gradeid FROM PurchaseContract WHERE SupplierId=2)

Using below query I can find the SupplierId, WeightLoaded, DeliveryDate, InvoiceAmount.

SELECT FP.SupplierId,SM.SupplierId,FP.WeightLoaded,FP.DeliveryDate,FP.InvoiceAmount 
FROM FundsPlanning FP
INNER JOIN SupplierMst SM
ON FP.SupplierId=SM.SupplierId and SM.SupplierId=2

How can I combine the result set of these two tables?

我如何获取两个没有外键关系的表的记录?

答案1

得分: 1

你可以尝试连接所有表,但需要注意表之间的关系(1-1、1-多、多-多),因为可能会出现重复行。

SELECT
    FP.SupplierId,
    SM.SupplierId,
    FP.WeightLoaded,
    FP.DeliveryDate,
    FP.InvoiceAmount,
    GM.GradeName
FROM 
    FundsPlanning FP
JOIN 
    SupplierMst SM ON FP.SupplierId = SM.SupplierId
JOIN 
    PurchaseContract PC ON PC.SupplierId = FP.SupplierId
JOIN 
    GradeMst GM ON GM.GradeId = PC.GradeId
WHERE 
    SM.SupplierId = 2
英文:

You could try to join all tables, but you need to take care of the relationships between tables (1-1, 1-many, many-many) because you could end up getting duplicate rows

SELECT
    FP.SupplierId,
    SM.SupplierId,
    FP.WeightLoaded,
    FP.DeliveryDate,
    FP.InvoiceAmount,
    GM.GradeName
FROM FundsPlanning FP, 
    SupplierMst SM,
    PurchaseContract PC,
    GradeMst GM
WHERE 
    FP.SupplierId = SM.SupplierId 
    AND PC.SupplierId = FP.SupplierId
    AND GM.GradeId = PC.GradeId
    AND SM.SupplierId = 2

huangapple
  • 本文由 发表于 2023年3月3日 18:26:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625874.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定