我有两个mysql表-销售表:
+----------------+------------------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+------------------------------+------+-----+---------+-------+ | StoreId | bigint(20) unsigned | NO | PRI | NULL | | | ItemId | bigint(20) unsigned | NO | | NULL | | | SaleWeek | int(10) unsigned | NO | PRI | NULL | | +----------------+------------------------------+------+-----+---------+-------+
和一个项目表:
+--------------------+------------------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------------+------------------------------+------+-----+---------+-------+ | ItemId | bigint(20) unsigned | NO | PRI | NULL | | | ItemName | varchar(100) | NO | | NULL | | +--------------------+------------------------------+------+-----+---------+-------+
sales表包含每个 ItemID的 多个记录-每个 SaleWeek一个 。我想通过加入两个表来选择出售的所有商品,如下所示:
SELECT items.ItemName, items.ItemId FROM items JOIN sales ON items.ItemId = sales.ItemId WHERE sales.StoreID = ? ORDER BY sales.SaleWeek DESC;
但是,这将基于每个 SaleWeek* 的多个条目返回多个 ItemId 值。我可以做一个单独的选择,只返回一个 ItemID 吗?-我不想查询最新的 SaleWeek, 因为有些项目可能没有最新的 SaleWeek 的条目,所以我需要获得最后一次销售。我需要指定 DISTINCT 还是使用 LEFT OUTER JOIN之类的 东西? ***
A DISTINCT应该做您想要的:
DISTINCT
SELECT DISTINCT items.ItemName, items.ItemId FROM items JOIN sales ON items.ItemId = sales.ItemId WHERE sales.StoreID = ? ORDER BY sales.SaleWeek DESC;
那只会返回不同的items.ItemName, items.ItemId元组。
items.ItemName, items.ItemId