2010-08-10 62 views
1

有什么方法可以从表连接中返回空白/空数据的不同值。最好用下面的例子来解释一下。从mysql连接查询中返回distinct和null记录

表 “订单”

order_id | order_total 
1  | 10 
2  | 20 
3  | 50 

表 “ORDER_ITEMS”

item_id | order_id | name  | qty_ordered | base_price | row_total 
1  | 1  | Product | 1   | 10   | 10 
2  | 2  | Product | 1   | 10   | 10 
3  | 2  | Product2 | 1   | 10   | 10 
4  | 3  | Product | 2   | 10   | 20 
5  | 3  | Product2 | 3   | 10   | 30 

我想产生一个结果集,看起来像这样。

order_id | item_id | name  | qty_ordered | base_price | row_total | order_total 
1  | 1  | Product | 1   | 10   | 10  | 10 
2  | 2  | Product | 1   | 10   | 10  | 20 
null  | 3  | Product2 | 1   | 10   | 10  | null 
3  | 4  | Product | 2   | 10   | 20  | 50 
null  | 5  | Product2 | 3   | 10   | 30  | null 

我只想要order_id和order_total每个订单一次。我认为这是可能的某种联接/独立/子查询,但唉,我已经尝试过迄今为止工作。

回答

1

用途:

SELECT x.order_id, 
     x.item_id, 
     x.name, 
     x.qty_ordered, 
     x.base_price, 
     x.row_total, 
     x.order_total 
    FROM (SELECT CASE 
        WHEN @order = o.order_id THEN NULL 
        ELSE o.order_id 
       END AS order_id, 
       oi.item_id, 
       oi.name, 
       oi.qty_ordered, 
       oi.base_price, 
       oi.row_total, 
       o.order_total, 
       CASE 
        WHEN @order = o.order_id THEN NULL 
        ELSE o.order_total 
       END AS order_total, 
       @order := o.order_id 
      FROM ORDER_ITEMS oi 
      JOIN ORDERS o ON o.order_id = oi.order_id 
      JOIN (SELECT @order := -1) r 
     ORDER BY o.order_id, oi.item_id) x 
+0

你总是让你的SQL的样子太美了,我需要你全面整理我的代码。 – 2010-08-10 02:16:32

+0

哇!太棒了。是的,如此优雅的呈现,现在看起来很简单。有点。 非常感谢。 – Bobby 2010-08-10 03:13:01

0
SELECT * FROM order_items 
LEFT JOIN orders 
ON (
    order_items.order_id=orders.order_id 
AND 
    order_items.item_id=(
     SELECT MIN(item_id) 
     FROM order_items a 
     WHERE a.order_id=order_items.order_id 
    ) 
) 

这应该工作,因为嵌套查询总是为每个订单返回相同的MIN(item_id),并且它只为该项目加入。

但是这是一个非常非常丑陋的sql片段。不要这样做。