SQL子查询问题

时间:2016-04-26 04:52:45

标签: mysql sql

无法捕获

上的子查询输出

有我的SQL代码

SELECT Txn.TrnID, Txn.Date, Txn.Amount,
(SELECT `MetaValue` FROM `meta` WHERE `Parent` = 'DB_Transaction' AND `MainID` = Txn.TrnID AND `MetaKey` = 'SalesID' AND `MetaValue` = '803') AS SubqueryResult
FROM transaction as Txn
WHERE SubqueryResult = '803'
LIMIT 10

我收到此错误

  

'where子句'中的未知列'SubqueryResult'

2 个答案:

答案 0 :(得分:3)

你可以尝试Stitch博士。

SELECT Txn.TrnID, Txn.Date, Txn.Amount, m.MetaValue FROM transaction as Txn inner join meta as m    on m.Parent = 'DB_Transaction' and m.MainID = Txn.TrnID AND m.MetaKey = 'SalesID' AND m.MetaValue = '803' LIMIT 10

答案 1 :(得分:1)

这是查询中的错误。您不能在where子句中使用AS valueName子查询结果。因为该名称将在执行整个查询后分配。因此,在where子句中,您的案例中找不到SubqueryResult列。

您可以做的是:(在Where子句中使用原始列名称)

SELECT Txn.TrnID, Txn.Date, Txn.Amount,
(SELECT `MetaValue` FROM `meta` WHERE `Parent` = 'DB_Transaction' AND `MainID` = Txn.TrnID AND `MetaKey` = 'SalesID' AND `MetaValue` = '803') AS SubqueryResult
FROM transaction as Txn
WHERE MetaValue = '803'
LIMIT 10