请问这个sql该怎么写???

netdottrue 2006-02-26 02:48:32
(主表 企业表)表A (enterprise_id,enterparise_name,desc)
(子表 企业分布区域表) 表B (id,enterprise_id,region_Id,desc)
A 、B是1对N关系
现在需要通过region_Id(区域Id)查询企业,区域可以多选,请问该如何写SQL???

我写的sql中有重复(企业)的记录
select a.enterprise_id,b.region_id from A a,B b where a.enterprise_id=b.enterprise_id and
(b.region_id="01"or b.region_id="02")
请问改如何去掉重复的记录,(如果一个企业对应多个区域,区域可以任选其中一个)

谢谢!!!!!!!!
...全文
342 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
goldarcher2005 2006-03-02
  • 打赏
  • 举报
回复
Select a.enterprise_id,min(b.region_id)
from A a,B b
Where a.enterprise_id=b.enterprise_id and
(b.region_id="01"or b.region_id="02")
Group By a.enterprise_id
guangli_zhang 2006-02-27
  • 打赏
  • 举报
回复
语句应该没错,你检查一下是不是数据的问题。
软猫克鲁 2006-02-27
  • 打赏
  • 举报
回复
不知道你是不是想让企业不重复找出相应的地区,如果是可以看看下面:
SELECT A.enterprise_id
,
(SELECT MAX(B.region_id)
FROM B
WHERE B.enterprise_id = A.enterprise_id
AND B.region_id IN ('01','02')
GROUP BY B.enterprise_id
) AS region_id
FROM A

区域有多个的时候只显示ID最大的一个,不知道合不合适。
47522341 2006-02-27
  • 打赏
  • 举报
回复
select a.enterprise_id,b.region_id
from A a,B b
where a.enterprise_id=b.enterprise_id and (b.region_id="01"or b.region_id="02") and rownum < 2
group by a.enterprise_id
pb_555 2006-02-26
  • 打赏
  • 举报
回复
楼主的问题我没有看得太懂,如果不想让企业重复可以考虑用union写sql

select a.enterprise_id,a.enterparise_name,a.desc
from A a,B b where a.enterprise_id=b.enterprise_id and b.region_id="01"
union
select a.enterprise_id,a.enterparise_name,a.desc
from A a,B b where a.enterprise_id=b.enterprise_id and b.region_id="02"
union
......

wucheng2008 2006-02-26
  • 打赏
  • 举报
回复
如果一个企业属于两个地区,则上面的语句就有重复记录
select distinct a.enterprise_id,a.enterparise_name,a.desc
from A a
where a.enterprise_id= (select distinct b.enterprise_id from B b where
b.region_id="01"or b.region_id="02")
netdottrue 2006-02-26
  • 打赏
  • 举报
回复

select distinct a.enterprise_id,a.enterparise_name,a.desc
from A a,B b
where a.enterprise_id=b.enterprise_id
and (b.region_id="01"or b.region_id="02")

这样会使企业信息重复!!!!!!!

hot.wind 2006-02-26
  • 打赏
  • 举报
回复
如果仅仅是要取得企业的id,只需要查询表B就可以了。如下:
select distinct b.enterprise_id
from B b
where (b.region_id="01"or b.region_id="02")

如果要得到企业的相关信息,则需要进行关联:
select distinct a.enterprise_id,a.enterparise_name,a.desc
from A a,B b
where a.enterprise_id=b.enterprise_id
and (b.region_id="01"or b.region_id="02")
netdottrue 2006-02-26
  • 打赏
  • 举报
回复
distinct 实现不了啊,显示的字段中一定要有个区域,如果区域有多个就显示一个,如果没有显示为空
tomuno 2006-02-26
  • 打赏
  • 举报
回复
distinct
netdottrue 2006-02-26
  • 打赏
  • 举报
回复
补充,region_id 这个条件也可以不要,就是说,查询企业时的区域字段不是必选的,区域也可一没有非配

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧