两表连接,取出其中某些项不重复的数据

联系:手机/微信(+86 17813235971) QQ(107644445)

标题:两表连接,取出其中某些项不重复的数据

作者:惜分飞©版权所有[未经本人同意,不得以任何形式转载,否则有进一步追究法律责任的权利.]

有省、市数据库表,现在要求只取每一个省中的一个市出来
数据库脚步如下
省表:

CREATE TABLE [dbo].[mem_province](
 [id] [int] NOT NULL,
  [nvarchar](6) NOT NULL,
 [name] [nvarchar](40) NULL,
 CONSTRAINT [PK_mem_province] PRIMARY KEY CLUSTERED
(
  ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


市表:

CREATE TABLE [dbo].[mem_city](
 [id] [int] NOT NULL,
  [nvarchar](6) NOT NULL,
 [name] [nvarchar](50) NULL,
 [provinceId] [nvarchar](6) NULL,
 CONSTRAINT [PK_mem_city] PRIMARY KEY CLUSTERED
(
  ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


执行sql语句为:

SELECT *
FROM   (
 SELECT a.id aid,
 a.code acode,
 a.name aname,
 b.id bid,
 b.code bcode,
 b.name bname,
 b.provinceId bprovinceId
 FROM   mem_province a left   JOIN
 mem_city b
 on  a.code= b.provinceId
 )c
WHERE  NOT   EXISTS (
 SELECT 1
 FROM   (SELECT a.id aid,
 a.code acode,
 a.name aname,
 b.id bid,
 b.code bcode,
 b.name bname,
 b.provinceId bprovinceId
 FROM   mem_province a LEFT   JOIN
 mem_city b
 on  a.code= b.provinceId)e
 WHERE  e.bid<c.bid
 AND  e.aname = c.aname
) ORDER BY aid

结果如:

发表评论

邮箱地址不会被公开。 必填项已用*标注

8 − 3 =