简体   繁体   English

SQL JOIN表具有多个具有相同ID的实例

[英]SQL JOIN tables where have multiple instances of the same id

I have two tables within the same database; 我在同一数据库中有两个表; tableA has the date I need while tableB has the cost . tableA有我需要的date而tableB有cost These tables are like an archive of changing dates and costs so a single item is repeated multiple times but I only want the most recent date and lowest cost . 这些表就像是更改日期和成本的存档,因此单个项目要重复多次,但是我只希望最近的date和最低的cost

Data example: 数据示例:

tableA 表A

  LocalSKU: aaa-aaa1 date: 12/1/1
  LocalSKU: aaa-aaa1 date: 11/1/3
  LocalSKU: aaa-aaa1 date: 10/2/1

tableB 表B

  SKU: aaa-aaa1 cost: 0.15
  SKU: aaa-aaa1 cost: 5
  SKU: aaa-aaa1 cost: 0

Desired result: 所需结果:

SKU: aaa-aaa1 date: 12/1/1 cost: 0

I've tried a simple query to pull back a single result with this query: 我试过一个简单的查询,以通过此查询拉回单个结果:

SELECT MAX(date) 
FROM tableA 
WHERE LocalSKU = (SELECT MIN(cost) 
                  FROM tableB 
                  WHERE SKU = tableB.LocalSKU GROUP BY SKU);

which yielded 0 results. 产生0个结果。

I'm new to subquerying and joining, is there a single query that can be made to get the desired result? 我是子查询和联接的新手,是否可以进行单个查询以获得所需的结果? I'm able to get the information I want in separate queries, but I got stuck trying to merge the arrays to combine the desired information. 我能够在单独的查询中获得所需的信息,但是在尝试合并数组以合并所需的信息时遇到了麻烦。

Help is much appreciated! 非常感谢帮助!

Join the tables and use the aggregation function on the result. 连接表并在结果上使用聚合函数。

SELECT a.localsku, MIN(cost), MAX(date)
FROM tableA
JOIN tableB ON a.localsku = b.sku
GROUP BY a.localsku

Actually, it will probably be more performant to do the grouping first and then join the subqueries, since joining large tables is expensive. 实际上,首先进行分组然后再加入子查询可能会更有效率,因为加入大表的成本很高。

SELECT a.localsku, a.date, b.cost
FROM (
    SELECT localsku, MAX(date) AS date
    FROM tableA
    GROUP BY localsku) AS a
JOIN (
    SELECT sku, MIN(cost) as cost
    FROM tableB
    GROUP BY sku) AS b
ON a.localsku = b.sku

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM