我有两张表有序产品和产品原料。这是表结构:
orderedproducts表:
+-----+---------+-----------+----------+--------------+
| id | orderid | productid | quantity | productgroup |
+-----+---------+-----------+----------+--------------+
| 117 | 1016186 | 265385 | 5 | Main |
| 118 | 1016186 | 407454 | 6 | Main |
| 119 | 1016186 | 975045 | 7 | Main |
| 120 | 1016186 | 975046 | 8 | Main |
+-----+---------+-----------+----------+--------------+
productsinstocks表:
+----+---------+-----------+----------+
| id | stockid | productid | quantity |
+----+---------+-----------+----------+
| 20 | 903958 | 265385 | 200 |
| 21 | 903958 | 407454 | 205 |
| 22 | 903958 | 975045 | 210 |
+----+---------+-----------+----------+
如您所见,该商品在orderedproducts表中只有三种类型的产品。我想加入这些表来实现以下结果:
+---------+-----------+---------+-----------+------------+
| orderid | productid | stockid | order_qty | stock_qty |
+---------+-----------+---------+-----------+------------+
| 1016186 | 265385 | 903958 | 5 | 200 |
| 1016186 | 407454 | 903958 | 6 | 205 |
| 1016186 | 975045 | 903958 | 7 | 210 |
| 1016186 | 975046 | 903958 | 8 | NULL |
+---------+-----------+---------+-----------+------------+
我使用了以下查询:
SELECT op.orderid, op.productid, plo.stockid, op.quantity order_qty, plo.quantity stock_qty FROM orderedproducts op
LEFT JOIN productsinstocks plo
ON op.productid=plo.productid
WHERE op.orderid=1016186
AND plo.stockid=903958
但它给了我以下结果:
+---------+-----------+---------+-----------+------------+
| orderid | productid | stockid | order_qty | stock_qty |
+---------+-----------+---------+-----------+------------+
| 1016186 | 265385 | 903958 | 5 | 200 |
| 1016186 | 407454 | 903958 | 6 | 205 |
| 1016186 | 975045 | 903958 | 7 | 210 |
+---------+-----------+---------+-----------+------------+
我不知道我错过了什么。
答案 0 :(得分:5)
WHERE
子句中的以下条件负责结果集中缺少的记录:
WHERE plo.stockid = 903958
orderedproducts
表中缺少的记录与productsinstocks
表中的任何记录都不匹配。因此,此记录的stockid
值为NULL
,您当前的WHERE
条件会将其过滤掉。
相反,在OR plo.stockid IS NULL
子句中添加一个WHERE
检查以保留此记录:
SELECT op.orderid, op.productid, plo.stockid, op.quantity order_qty,
plo.quantity AS stock_qty
FROM orderedproducts op
LEFT JOIN productsinstocks plo
ON op.productid = plo.productid
WHERE op.orderid = 1016186 AND
(plo.stockid = 903958 OR plo.stockid IS NULL)
在这里演示:
答案 1 :(得分:2)
试试这个
SELECT op.orderid, op.productid, plo.stockid, op.quantity order_qty, plo.quantity stock_qty FROM orderedproducts op
LEFT JOIN productsinstocks plo
ON op.productid=plo.productid AND plo.stockid=903958
WHERE op.orderid=1016186
答案 2 :(得分:0)
首先,让我们看看 WHERE 和 ON 条款
其中子句决定为输出选择哪些行。
ON 子句决定为连接选择哪些行。
WHERE plo.stockid=903958
WHERE 子句的这一部分消除了输出中的最后一行。
这里我们要在连接操作之前选择行。因此,我们可以将条件从 WHERE 移到 ON 子句。
SELECT op.orderid, op.productid, plo.stockid, op.quantity order_qty, plo.quantity stock_qty FROM orderedproducts op
LEFT JOIN productsinstocks plo
ON op.productid=plo.productid AND plo.stockid=903958 AND op.orderid=1016186
此外,您应该在最后一行预期 stockid 为 NULL 而不是 903958 。