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

联系:手机/微信(+86 17813235971) QQ(107644445)QQ咨询惜分飞

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

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

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

数据库脚步如下

省表:

CREATE TABLE [dbo].[mem_province](
 [id] [int] NOT NULL,
 1 [nvarchar](6) NOT NULL,
 [name] [nvarchar](40) NULL,
 CONSTRAINT [PK_mem_province] PRIMARY KEY CLUSTERED
(
 1 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,
 1 [nvarchar](6) NOT NULL,
 [name] [nvarchar](50) NULL,
 [provinceId] [nvarchar](6) NULL,
 CONSTRAINT [PK_mem_city] PRIMARY KEY CLUSTERED
(
 1 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

结果如:

此条目发表在 SQL Server 分类目录。将固定链接加入收藏夹。

评论功能已关闭。