我厚吗? MySQL:LEFT JOIN上的“不唯一表/别名”

时间:2012-03-12 13:48:55

标签: mysql sql left-join

我有以下SQL语句,它返回“ Not unique table / alias ”。我很确定我在这里遗漏了一些明显的东西,在引用StockID时可能不够具体,因为它是StockSuppliersStock的常用字段名称。 Stock中的主键,SuppliersStock

中的外键
SELECT Stock.BuyingPrice, SuppliersStock.StockID, SuppliersStock.Quantity
FROM Stock
LEFT JOIN Stock on Stock.StockID = SuppliersStock.StockID 
WHERE Stock.StockID = <some-integer />

Stock表包含有关库存的具体信息,Suppliers包含供应商信息,SuppliersStock包含新库存的信息订单,其中包含对Stock和{{的外键引用1}}。

我想要做的是返回Suppliers(来自BuyingPrice),StockStockID(来自Quantity)字段,以便我可以制作一个订购新库存的成本清单。

免责声明:我知道,有关SQL连接的另一个问题。别伤害我!我用谷歌搜索过,我已经搜索过但我有点糊涂了,我老老实实地试图寻找一个类似的问题,以了解更多关于我能做些什么来解决这个问题,但是得到了王牌。请帮帮忙?

4 个答案:

答案 0 :(得分:9)

你的'from'和'left join'都引用了同一个表'Stock'。更改其中一个以参考'SupplierStock'

答案 1 :(得分:7)

您似乎正在跳过SuppliersStock的别名,或者它是一个不同的表:

/* If SuppliersStock is a different table */
SELECT Stock.BuyingPrice, SuppliersStock.StockID, SuppliersStock.Quantity
FROM Stock
LEFT JOIN SuppliersStock on Stock.StockID = SuppliersStock.StockID 
WHERE Stock.StockID = <some-integer />

/* If SuppliersStock is the same table, needing an alias */
SELECT Stock.BuyingPrice, SuppliersStock.StockID, SuppliersStock.Quantity
FROM Stock
LEFT JOIN Stock AS SuppliersStock on Stock.StockID = SuppliersStock.StockID 
WHERE Stock.StockID = <some-integer />

答案 2 :(得分:0)

问题是你加入Stock Stock而不是SuppliersStock,所以当你说Stock.StockID MySQL不知道你指的是哪两个至。

我猜你想要这样做:

SELECT Stock.BuyingPrice, SuppliersStock.StockID, SuppliersStock.Quantity
FROM Stock
LEFT JOIN SuppliersStock on Stock.StockID = SuppliersStock.StockID 
WHERE Stock.StockID = <some-integer />

答案 3 :(得分:0)

您正在加入Stock本身,这意味着查询不知道您正在引用哪个Stock。 如果这是您想要的,请为联接表创建别名:JOIN Stock AS SuppliersStock