问题: 我有一个库存表和一个列出正在拍卖的物品的表格。我想要一个别名字段(“isAuction”)来表示拍卖品表中是否存在具有库存库存号的商品。
我写了以下查询:
SELECT FROM inventory AS i
EXISTS(SELECT * FROM auctionitems AS a WHERE a.stockNo = i.stockNo) AS "isAuction"
这会根据需要填充“isAuction”字段,其中包含1或0。
我现在添加一个WHERE条件:
SELECT FROM inventory AS i
EXISTS(SELECT * FROM auctionitems AS a WHERE a.stockNo = i.stockNo) AS "isAuction"
WHERE isAuction = 1
但是,当我添加一个WHERE条件时,我收到一个错误: “#1054 - 'where子句'中的未知列'isAuction'”
两个问题: 1)我在哪里弄错了? 2)有没有更好的方法来解决我的问题?
答案 0 :(得分:2)
SELECT i.*
FROM inventory AS i
WHERE EXISTS(SELECT * FROM auctionitems AS a WHERE a.stockNo = i.stockNo)
答案 1 :(得分:2)
尝试HAVING isAuction = 1
。
我在某处读到HAVING比WHERE更清醒的计算列。
答案 2 :(得分:1)
您无法在WHERE
中使用别名。你可以做到
WHERE EXISTS(SELECT * FROM auctionitems AS a WHERE a.stockNo = i.stockNo)
或者您可以将条件放入HAVING
子句(mysql允许您使用HAVING
而不使用聚合函数):
HAVING isAuction = 1
另外,你可以写
SELECT * FROM
(SELECT i.*,
EXISTS(SELECT * FROM auctionitems AS a WHERE a.stockNo = i.stockNo) AS isAuction
FROM inventory AS i
)a
WHERE a.isAuction = 1