从具有可能重复的2个表中选择数据

时间:2014-10-21 17:36:33

标签: mysql

我在表A中有81,190个城镇名称,列名为:TownName。

我有以下列方式存储在tableB中的32,117个唯一记录名称列表:Town,County,Volume。

我想为81,190个城镇名称中的每个城镇取名。所以我的查询如下

Select TownName, County, Volume
From tableA
Inner Join tableB
On TownName = Town
Where Town = TownName
Order By TownName, Volume, County

在所有条件相同的情况下,我希望获得81,190条记录。

但是,我得到了91,669条记录。我明白为什么会这样。城镇名称可以在tableB中出现多次,因为相同的城镇名称可以在多个县。

返回的记录示例为:

Abinton Limerick 0
Abinton Limerick 0
Abinton Lanarkshire 11
Abinton Lanarkshire 11
Abinton Northamptonshire 13
Abinton Northamptonshire 13

Abington在tableA中出现两次,在tableB中出现3次,而在我要求的2上返回6条记录。

我应该如何修改我的查询,以便返回具有最高音量的县,例如:

Abinton Northamptonshire 13
Abinton Northamptonshire 13

我最终获得了81,190条记录。

提前感谢您的帮助。

4 个答案:

答案 0 :(得分:2)

也许你可以使用窗口函数MAX。 类似的东西:

Select TownName, County, Volume
From 
(Select TownName, County, Volume, max(Volume) over (partition by TownName) as highest_volume
From tableA
Inner Join tableB
On TownName = Town) as x
where Volume = x.highest_volume
Order By TownName, Volume, County

修改

这是重现您情况的正确方法吗?

create table tableA (
TownName varchar(100)
);

create table tableB (
Town varchar(100),
County varchar(100),
Volume integer
);

insert into tableA values('Abinton');
insert into tableA values('Abinton');
insert into tableB values('Abinton','Limerick',0);
insert into tableB values('Abinton','Lanarkshire',11);
insert into tableB values('Abinton','Northamptonshire',13);

答案 1 :(得分:0)

尝试以下查询

CREATE TEMPORARY TABLE IF NOT EXISTS tableC AS (SELECT DISTINCT Town, County FROM tableB);
Select  TownName, County
 From tableA
 Left Join tableC
 On tableA.TownName = tableC.Town
 Order By TownName, Volume;

虽然我认为你的描述令人困惑。您描述了"我有一个32,117个唯一记录名称列表,存储在表B"和#34;城镇名称可以在表格B"中出现多次。如果在TableA中出现这种情况,您会有独特的tawon名称吗?如果不是,您在加入表格时总是会有重复

答案 2 :(得分:0)

如果您使用的是MySQL,则此查询必须有效:

SELECT
  a.TownName,
  (SELECT b1.County FROM tableB b1
   WHERE b1.Town = a.TownName AND b1.Volume = b.max_volume
   LIMIT 1) AS Country,
  b.max_volume AS Volume
FROM tableA a
INNER JOIN (
  SELECT Town, MAX(Volume) AS max_volume
   FROM tableB
   GROUP BY Town
) b ON b.Town = a.TownName
ORDER BY a.TownName, County

如果您的数据库服务器支持窗口函数,那么查询可以更简单:

SELECT a.TownName, b.County, b.Volume
FROM tableA a
INNER JOIN (
  SELECT Town, County, Volume,
    ROW_NUMBER() OVER (PARTITION BY Town ORDER BY Volume DESC) rn  
  FROM tableB
) b
ON b.Town = a.TownName AND b.rn = 1
ORDER BY a.TownName, b.County

答案 3 :(得分:0)

如果我理解正确,你需要表A中所有城镇的县名。所以你可以试试以下内容:

Select tableA.TownName, tableB.County, tableB.Volume
From tableA
left Join tableB
On tableA.TownName = tableB.Town
Where tableB.Volume= (select max(tB.Volume) from tableB as tB Where tB.Town = tableB.Town)
Order By tableA.TownName, tableB.County, tableB.Volume