[英]MySQL COUNT Sub-query with SELECT *
I have a table of inventory items (holds description, details of item etc.), a table of stock (physical items that we have - items of inventory), and a suppliers table (who supply the stock, but may differ from time to time). 我有一个库存项目表(货品描述,项目明细等),一个库存表(我们拥有的物理物料-库存项目)和一个供应商表(谁提供库存,但有时可能会有所不同)时间)。
Suppliers -- Stock -- Inventory 供应商-库存-库存
Inventory has many stock. 库存很多。 Suppliers have many stock. 供应商有很多库存。 Stock has one supplier, and one inventory 库存中有一个供应商和一个库存
I'm trying to run a query to get all data from inventory, and count how many suppliers it has through a sub query. 我正在尝试运行查询以从库存中获取所有数据,并通过子查询计算它有多少供应商。 However, I need to use SELECT * 但是,我需要使用SELECT *
What I have at the moment: 我目前所拥有的:
SELECT
( SELECT COUNT(DISTINCT SupplierID)
FROM Stock
WHERE Stock.InventoryID = Inventory.ID
) AS Suppliers
, *
FROM `Inventory`;
I've tried variations on this, swapping the field order (seen this elsewhere on this site), changing the sub-query etc. 我已经尝试过对此进行变体,交换字段顺序(在此站点的其他地方看到过),更改子查询等。
However, it tells me there's an error near '* FROM'. 但是,它告诉我'* FROM'附近有错误。 Can anyone suggest a way to do this query please? 任何人都可以建议一种方法来执行此查询吗?
Use table aliases: 使用表别名:
SELECT (SELECT COUNT(DISTINCT s.SupplierID)
FROM Stock s
WHERE s.InventoryID = i.ID
) AS Suppliers, i.*
FROM `Inventory` i;
The need for a qualification on *
is described in the documentation : 文档中描述了对*
资格的需求:
Use of an unqualified
*
with other items in the select list may produce a parse error. 选择列表中的其他项目使用不合格*
可能会产生解析错误。 To avoid this problem, use a qualifiedtbl_name.*
reference 为避免此问题,请使用合格的tbl_name.*
参考。SELECT AVG(score), t1.* FROM t1 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.