我有一个现有的查询,它提供了所需的结果 - 但是我需要从另一个表中添加一个列并仍然获得相同的203行...当我尝试加入该表时,我得到了数千行...
select a.state, a.alternate_id, a.reg_id
from altid1 a, altid1 b
where a.alternate_id=b.alternate_id
and a.reg_id <> b.reg_id
group by a.state, a.alternate_id, a.reg_id
having count(a.alternate_id)>1
order by state, alternate_id,reg_id;
这给了我状态和每个具有多个reg_ids的备用ID ...现在我需要添加altid1表中不存在的两个所有者字段
我需要加入所有者表并获得与其他列相同的203结果...所有者表DOES包含reg_id列但是当我试图得到那些时,我怎么能匹配在原始表中有不同的reg_ids?
select a.state, a.alternate_id, a.reg_id, c.owner1, c.ownertype1
from altid1 a, altid1 b, owner c
where a.alternate_id=b.alternate_id
and a.reg_id <> b.reg_id
group by a.state, a.alternate_id, a.reg_id, c.owner1, c.ownertype1
having count(a.alternate_id)>1
order by state, alternate_id, reg_id;
感谢您的帮助!
答案 0 :(得分:0)
试试他的那个,确保你将[id列]更改为实际的字段名称,并且a或b表与c表有关系。
select a.state, a.alternate_id, a.reg_id, c.owner1, c.ownertype1
from altid1 a, altid1 b, owner c
where a.alternate_id=b.alternate_id
and a.reg_id <> b.reg_id
and c.[id column] = a or b . [id column] -- change id column to actual id field from the table and change a or b to the correct table having relationship with c table.
group by a.state, a.alternate_id, a.reg_id, c.owner1, c.ownertype1
having count(a.alternate_id)>1
order by state, alternate_id, reg_id;
答案 1 :(得分:0)
当您将owner
添加到您正在选择的表时,您没有添加其他连接条件。这意味着您在原始的203行结果与owner
之间执行交叉联接。
两个表A
和B
之间的交叉联接为每个可能的行对返回一行,其中A
中有一行,B
中有一行。因此,如果A
有n
行而B
有m
行,则A
交叉加入B
有m*n
行。不好。
您需要做的是在where语句中添加一个附加子句。我无法确切地告诉你代码会是什么。是否有一些专栏将owner
与altid1
相关联?
但是,或许更重要的是,不要使用逗号连接。他们很容易意外地创建交叉连接和许多其他可怕的可怕事情。如果您不小心在大型数据库上进行交叉连接,则最终可能会有数百万行。
而是仅使用where子句来过滤结果并使用标准JOIN
语法连接其他表。
您的原始查询将变为:
select a.state, a.alternate_id, a.reg_id
from altid1 a
inner join altid1 b
on a.alternate_id = b.alternate_id
where a.reg_id <> b.reg_id
group by a.state, a.alternate_id, a.reg_id
having count(a.alternate_id)>1
order by state, alternate_id,reg_id;
然后您的新查询会显示如下(我只是猜测owner
到altid1
的链接:
select a.state, a.alternate_id, a.reg_id
from altid1 a
inner join altid1 b
on a.alternate_id = b.alternate_id
inner join owner c
on c.owner_id = a.owner_id
where a.reg_id <> b.reg_id
group by a.state, a.alternate_id, a.reg_id
having count(a.alternate_id)>1
order by state, alternate_id,reg_id;
请注意,我使用了内连接!我无法告诉您是否应该使用内部联接或左联接来引入owner
。对差异的简短解释是内连接不包括无法找到owner
中匹配行的行。
P.S。 不要使用逗号连接