我有以下表格结构:
发货(将IDDestination作为外键) - >目的地(将IDCity作为外键) - > City(将IDCountry作为外键)。
我想为我的存储过程提供一个国家/地区ID,并让它返回所有货件。我如何使用纯SQL语法执行此操作?我可以用ORM来做这件事,但我强迫自己学习这个。
答案 0 :(得分:2)
对于visual demonstration of various JOINs, see this link。
假设@idcountry是整数数据类型,请使用:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE get_shipments_for_countryid
@idcountry INT
AS
BEGIN
SELECT DISTINCT
s.*
FROM SHIPMENT s
JOIN DESTINATION d ON d.id = s.iddestination
JOIN CITY c ON c.id = d.idcity
WHERE c.idcountry = @idcountry
END
GO
将参数数据类型(如果不是INT)更改为适当的值。
如果任何表格是多对多或一对多的话,DISTINCT
是必要的......
答案 1 :(得分:1)
SELECT s.*
FROM City c INNER JOIN (
Shipment s INNER JOIN Destination d ON s.IDDestination = d.ID)
ON c.ID = d.IDCity
WHERE c.IDCountry = @IDCountry
答案 2 :(得分:0)
您可以使用INNER JOIN将所有表链接在一起。
CREATE GetShipments
@CountryID int
AS
SELECT *
FROM Shipments
INNER JOIN Destination ON Shipment.IDDestination = Destination.ID
INNER JOIN Cities ON Destination.IDCity = Cities.ID
WHERE Cities.IDCountry = @CountryID
答案 3 :(得分:0)
像这样......也可能......
select * from Shipment as s
inner join Destination as d on s.IDDestination = d.IDDestination
inner join City as c on d.IDCountry = c.IDCountry
where c.IDCountry = @CountryID
答案 4 :(得分:0)
SELECT S.*
FROM Shipment S
JOIN Destination D on S.IDDestination = D.ID
JOIN City C on D.IDCity = C.ID
WHERE IDCountry = @IDCountry