我对如何在一个查询中减去子查询提出了挑战。我不知道这是否可行或是否有办法绕过它。我感谢任何帮助,我可以得到。感谢。
$query = SELECT name, email, (SELECT SUM(tx_amount) FROM #__tx WHERE (tx_from = id
AND tx_from_code = code AND tx_type1 = 'Credit' AND tx_status = 'Approved') OR
(tx_to = id AND tx_to_code = code AND tx_type2 = 'Credit' AND tx_status = 'Approved')) as Wallet_Balance,
(SELECT SUM(tx_amount) FROM #__tx WHERE (tx_from = id AND tx_from_code = code AND
tx_type1 = 'Debit' AND tx_status = 'Approved') OR (tx_to = id AND tx_to_code = code AND
tx_type2 = 'Debit' AND tx_status = 'Approved')) as Wallet_Balancee, (Wallet_Balance-Wallet_Balancee) as Total FROM users WHERE id = '$id');
我一直收到错误未知列' Wallet_Balance'在'字段列表' 请帮忙。 感谢
答案 0 :(得分:0)
这是您的查询。问题很简单。您不能在同一select
子句中使用列别名。
SELECT name, email,
(SELECT SUM(tx_amount)
FROM #__tx
WHERE (tx_from = id AND tx_from_code = code AND
tx_type1 = 'Credit' AND tx_status = 'Approved'
) OR
(tx_to = id AND tx_to_code = code AND
tx_type2 = 'Credit' AND tx_status = 'Approved'
)
) as Wallet_Balance,
(SELECT SUM(tx_amount)
FROM #__tx
WHERE (tx_from = id AND tx_from_code = code AND
tx_type1 = 'Debit' AND tx_status = 'Approved'
) OR
(tx_to = id AND tx_to_code = code AND
tx_type2 = 'Debit' AND tx_status = 'Approved'
)
) as Wallet_Balancee,
(Wallet_Balance-Wallet_Balancee) as Total
FROM users
WHERE id = '$id';
您有几种选择。最简单的可能就是使用子查询:
SELECT name, email, Wallet_Balance, Wallet_Balancee,
(Wallet_Balance-Wallet_Balancee) as Total
FROM (SELECT name, email,
(SELECT SUM(tx_amount)
FROM #__tx
WHERE (tx_from = id AND tx_from_code = code AND
tx_type1 = 'Credit' AND tx_status = 'Approved'
) OR
(tx_to = id AND tx_to_code = code AND
tx_type2 = 'Credit' AND tx_status = 'Approved'
)
) as Wallet_Balance,
(SELECT SUM(tx_amount)
FROM #__tx
WHERE (tx_from = id AND tx_from_code = code AND
tx_type1 = 'Debit' AND tx_status = 'Approved'
) OR
(tx_to = id AND tx_to_code = code AND
tx_type2 = 'Debit' AND tx_status = 'Approved'
)
) as Wallet_Balancee
FROM users
WHERE id = '$id';
) w;
您只为一个用户选择数据,因此创建派生表的开销非常小。