我有这个存储过程:
ALTER PROCEDURE [dbo].[Get_All_Items]
AS
BEGIN
SELECT
ItemID, ItemName, CategoryID, CountryID,
ItemSize, ColorID, ProductionDate, ExpiryDate,
UnitName, FirstUnitBarcode, FirstItemQuantity,
FirstUnitDefult, FirstUnitLimit,
UnitsTbl.SecondUnit, SecondUnitBarcode, SecondItemQuantity,
SecondUnitDefult, SecondUnitLimit,
ThirdUnit, ThirdUnitBarcode, ThirdItemQuantity,
ThirdUnitDefult, ThirdUnitLimit, UnitDefult,
ItemImage, ItemStatus, ItemsMainTbl.Nots,
ItemsMainTbl.CreatedBy, ItemsMainTbl.CreatedDate,
ItemsMainTbl.ModifiedBy, ItemsMainTbl.ModifiedDate
FROM
ItemsMainTbl
INNER JOIN
UnitsTbl ON ItemsMainTbl.FirstUnit = UnitsTbl.UnitID
INNER JOIN
UnitsTbl ON ItemsMainTbl.SecondUnit = UnitsTbl.UnitID
END
条件:
如何在该公共列上连接所有三个表?
我只得到第一个
ItemsMainTbl.FirstUnit = UnitsTbl.UnitID
谢谢
答案 0 :(得分:1)
如果要多次连接同一个表,则需要为连接表的每个实例指定别名,如下所示:
SELECT *
FROM ItemsMainTbl
INNER JOIN UnitsTbl u1 ON ItemsMainTbl.FirstUnit = u1.UnitID
INNER JOIN UnitsTbl u2 ON ItemsMainTbl.SecondUnit = u2.UnitID
INNER JOIN UnitsTbl u3 ON ItemsMainTbl.ThirdUnit = u3.UnitID
然后在select语句中,您可以区分已连接的实例,如下所示:
SELECT u1.Barcode, -- Barcode from FirstUnit
u2.Barcode, -- Barcode from SecondUnit
u3.Barcode -- Barcode from ThirdUnit
答案 1 :(得分:0)
您需要为UnitsTbl定义参考。根据OOP,将这些引用视为同一类的新对象。此外,每次查询表时都使用引用是一个好习惯。
SELECT *
FROM
ItemsMainTbl t1
INNER JOIN
UnitsTbl u1 ON t1.FirstUnit = u1.UnitID
INNER JOIN
UnitsTbl u2 ON t1.SecondUnit = u2.UnitID
INNER JOIN
UnitsTbl u3 ON t1.ThirdUnit = u3.UnitID