我在各自的表中选择了4个不同的列。 ProductID,ProductDesc,TransactionDate和TransactionPrice。
使用以下查询作为存在记录的示例:
SELECT transactionProducts.productID, products.productDesc, transactionDate, transactionProducts.price
FROM transactionProducts INNER JOIN transactions ON transactionProducts.transactionID = transactions.transactionID
INNER JOIN products on products.productID=transactionProducts.productID
WHERE (transactionProducts.productID='1011021' AND transactions.transactionDate='2017-01-07')
GROUP BY transactionProducts.productID, products.productDesc, transactionDate, transactionProducts.price
ORDER BY transactionDate
输出如下
ProductID | Product Desc | TransactionDate | TransactionPrice
1011021 | SD DOG | 2017-01-07 | $15
即使productID(例如1011021)与transactionDate没有关联,我的目标也是返回记录。以下查询查询不存在的日期
SELECT transactionProducts.productID, products.productDesc, transactionDate, transactionProducts.price
FROM transactionProducts INNER JOIN transactions ON transactionProducts.transactionID = transactions.transactionID
INNER JOIN products on products.productID=transactionProducts.productID
WHERE (transactionProducts.productID='1011021' AND transactions.transactionDate='2017-01-18')
GROUP BY transactionProducts.productID, products.productDesc, transactionDate,
ORDER BY transactionDate
我得到的当前输出是(没有找到记录):
ProductID | Product Desc | TransactionDate | TransactionPrice
| | |
我正在寻找的输出仍然会输出在查询中指定的productID productDesc和transactionDate,但将transactionPrice返回为0.
ProductID | Product Desc | TransactionDate | TransactionPrice
1011021 | SD DOG | 2017-01-18 | 0
如果给定的ProductID(1011021)的事务没有在给定的TransactionDate(2017-01-08)上发生,我想强制将transactionPrice设置为0,任何其他建议如何实现此?
答案 0 :(得分:0)
LEFT JOIN
代替INNER
和NULL
子句中允许transactions.transactionDate
transactionProducts.productID
和WHERE
,以便在其他表中没有相应记录时启用它们。FROM
子句后跟LEFT JOIN
。transactionProducts.price
显示为0
而不是NULL
,请将SELECT
中的内容更改为ISNULL(transactionProducts.price, 0)
。这样,(a)即使没有交易,所有产品也会出现;(b)WHERE
上的transactionDate
条款不排除缺失的记录:
SELECT transactionProducts.productID, products.productDesc, transactionDate, ISNULL(transactionProducts.price, 0)
FROM products
LEFT JOIN transactionProducts on products.productID = transactionProducts.productID
LEFT JOIN transactions ON transactionProducts.transactionID = transactions.transactionID
WHERE (transactionProducts.productID = '1011021' OR transactionProducts.productID IS NULL)
AND
(transactions.transactionDate = '2017-01-18' OR transactions.transactionDate IS NULL)
GROUP BY transactionProducts.productID, products.productDesc, transactionDate
ORDER BY transactionDate
(注意:transactionDate
如果在该日期没有该产品的任何交易,仍会显示为NULL
。因此,如果您想要显示其他默认日期,请申请同样ISNULL()
。)