从三个内部联接表中选择不同的值

时间:2014-04-10 06:47:05

标签: sql inner-join

我有三个表Order_InventoryOrder_ListTrack_Order。 当我在这里执行相同的查询时,我在gridView中获得了相同订单ID的复制值。 我想获得不同的价值观。附加文件是我的查询和数据库值的快照。

查询以Order_Id

为基础跟踪订单
SELECT
  Shopping_Order_List.Order_ID AS Order_ID, Shopping_Order_List.Product_ID,
  Shopping_Order_List.Product_Name, Shopping_Order_List.Order_Product_Quantity,
  Shopping_Order_List.Order_Discount, Shopping_Order_List.Order_Price,
  Shopping_TrackOrder.Track_ID, Shopping_TrackOrder.Status, Shopping_TrackOrder.Remarks
FROM Shopping_Order_Inventory
  INNER JOIN
    Shopping_Order_List ON Shopping_Order_Inventory.Order_ID = Shopping_Order_List.Order_ID
  INNER JOIN
    Shopping_TrackOrder ON Shopping_Order_Inventory.Order_ID = @OrderID

结果:

Track_ID  Product_ID  Product_Name  Status  Remarks         Order_ID
1         1           Nexus         False   Not Assembled   4
4         1           Nexus         True    Deliverd        4
7         1           Nexus         False   Stock Incoming  4
8         1           Nexus         False   Stock Incoming  4
1         2           Galaxy Young  False   Not Assembled   4
4         2           Galaxy Young  True    Deliverd        4
7         2           Galaxy Young  False   Stock Incoming  4
8         2           Galaxy Young  False   Stock Incoming  4
1         3           Galaxy S3     False   Not Assembled   4
4         3           Galaxy S3     True    Deliverd        4
7         3           Galaxy S3     False   Stock Incoming  4
8         3           Galaxy S3     False   Stock Incoming  4

如您所见,我为相同的订单ID重复了值

2 个答案:

答案 0 :(得分:0)

最后一个JOINed表没有链接链接

应该是

SELECT
...
FROM Shopping_Order_Inventory
  INNER JOIN
    Shopping_Order_List ON Shopping_Order_Inventory.Order_ID = Shopping_Order_List.Order_ID
  INNER JOIN
    Shopping_TrackOrder ON Shopping_Order_Inventory.Order_ID = @OrderID 
                        AND Shopping_Order_Inventory.Order_ID =Shopping_Order_Inventory.Order_ID

答案 1 :(得分:0)

对于一个订单更正,您有多个跟踪记录和相同的备注吗?

因此,要获得不同的行,您不应选择 track id 并使用 distinct 关键字来获取不同的行。

SELECT DISTINCT
  Shopping_Order_List.Order_ID AS Order_ID, Shopping_Order_List.Product_ID,
  Shopping_Order_List.Product_Name, Shopping_Order_List.Order_Product_Quantity,
  Shopping_Order_List.Order_Discount, Shopping_Order_List.Order_Price,
  Shopping_TrackOrder.Status, Shopping_TrackOrder.Remarks
FROM Shopping_Order_Inventory
  INNER JOIN
    Shopping_Order_List ON Shopping_Order_Inventory.Order_ID = Shopping_Order_List.Order_ID
  INNER JOIN
    Shopping_TrackOrder ON Shopping_Order_Inventory.Order_ID = @OrderID