SQL Join for Nonxistant Rows

时间:2016-01-28 04:37:32

标签: mysql sql sql-server postgresql

我有以下查询,但它只提取两个表中存在的记录。如果Table_Sold中不存在记录,我该如何修改它仍然会拉?

 SELECT  Col_1 ,
        Col_2 - Sold AS Remaining_Stock
FROM    Table_1
        JOIN ( SELECT   Col_3 ,
                        SUM(Col_2) AS Sold
               FROM     Table_2
               GROUP BY Col_3
             ) AS Table_Sold ON Table_1.Col_1 = Table_Sold.Col_3
                                AND Col_2 > Sold

3 个答案:

答案 0 :(得分:2)

您应该使用LEFT JOIN而不是常规JOIN

SELECT Col_1, Col_2 - coalesce(Sold, 0) AS Remaining_Stock
FROM Table_1
LEFT JOIN (
  SELECT Col_3, SUM(Col_2) AS Sold
  FROM Table_2
  GROUP BY Col_3) AS Table_Sold 
ON Table_1.Col_1 = Table_Sold.Col_3
   AND Col_2 > Sold; -- This last condition is probably ambiguous

答案 1 :(得分:0)

这将是LEFT JOIN情况

SELECT Col_1, Col_2 - Sold as Remaining_Stock 
FROM Table_1 
LEFT JOIN (
   SELECT Col_3, SUM(Col_2) as Sold 
FROM Table_2 GROUP BY Col_3) as Table_Sold
ON Table_1.Col_1 = Table_Sold.Col_3 AND Col_2 > Sold

答案 2 :(得分:0)

SELECT p.id, a.qty - ifnull(o.qty,0) remaining_stock
FROM products p
LEFT JOIN (
    SELECT product_id, sum(qty) qty
    FROM orders
    GROUP BY 1
) o ON p.id = o.product_id
WHERE a.qty > o.qty