我有两个SQL表:“借方”和“借方行项目”。我想对“借方”表运行一个SQL查询,其中每个借方记录都在“ Debits_Line_Items”表中包含对应记录的列表,应该与CartID值匹配。
这是我尝试过的操作,它产生了一个错误,即“ lineItems”列未知:
SELECT
CartID AS cartId,
TotalCost AS totalCost,
lineItems
FROM Debits
LEFT JOIN
(
SELECT
Price AS cost,
Quantity AS quantity,
TotalPrice as total
FROM Debits_Line_Items
WHERE UserID = 9902
) AS lineItems
ON Debits.CartID = lineItems.CartID
WHERE UserID = 9902
这就是我所希望的:
[
{
cartId: 3225,
totalCost: 212,
lineItems: [
{
cost: 32,
quantity: 1,
total: 32
},
{
cost: 60,
quantity: 3,
total: 180
},
},
{
cartId: 3226,
totalCost: 75,
lineItems: [
{
cost: 15,
quantity: 5,
total: 75
}
}
]
答案 0 :(得分:0)
尝试这样的事情:
WITH lineItems(cost, quantity, total, CartID) AS (
SELECT
Price AS cost,
Quantity AS quantity,
TotalPrice as total
FROM
Debits_Line_Items
WHERE
UserID = 9902
)
SELECT
d.CartID AS cartId,
d.TotalCost AS totalCost,
lineItems.*
FROM
Debits d
LEFT JOIN lineItems l
ON d.CartID = l.CartID
WHERE
d.UserID = 9902
让我知道是否有帮助。始终最好与雷斯特链接。然后,我们可以使用一些示例数据为您验证代码。