access过滤2张表中重复的数据 小弟愚昧,对过滤这些东西太模糊,希望大家在写完SQL语句时,加以说明。3Q
情况是这样的。现有 p_news表是放新闻的表:有字段 ID(自动增长),p_news_id(数字类型),p_news_name(新闻标题)
pinglun表,是用户评论内容表:有字段 ID(自动增长),pinglun_ID(跟表p_news表中p_news_id有对应关系),pinglun(评论内容)
下面是我写的。但是取出p_news_name会出现重复记录
sql = "select p_news.*,pinglun.* from p_news,pinglun where p_news.p_news_id=pinglun.pl_ID "
怎样去掉重复记录???
也就是说 新闻重复,比如pinglun表里的pinglun_ID 为57的对应p_news表里的p_news_id可能有很多新闻。所以pinglun表里的pinglun_ID和p_news表里的p_news_id是一对多的关系。
sql=" select distinct p_news.*,pinglun.* from p_news,pinglun where p_news.p_news_id=pinglun.pl_ID "
是不行的。我也试过了。
------解决方案--------------------按照你所说的,不可能重复
以下是SQL测试
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Test_001]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Test_001]
GO
CREATE TABLE [dbo].[Test_001] (
[id] [bigint] IDENTITY (1, 1) NOT NULL ,
[p_id] [numeric](18, 0) NOT NULL ,
[p_name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Test_002]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Test_002]
GO
CREATE TABLE [dbo].[Test_002] (
[id] [bigint] IDENTITY (1, 1) NOT NULL ,
[pl_id] [numeric](18, 0) NOT NULL ,
[pl_content] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO
insert into Test_001(p_id,p_name) values (57,'测试标题1')
insert into Test_001(p_id,p_name) values (57,'测试标题2')
insert into Test_001(p_id,p_name) values (57,'测试标题3')
insert into Test_002(pl_id,pl_content) values (57,'测试内容1')
insert into Test_002(pl_id,pl_content) values (58,'测试内容2')
insert into Test_002(pl_id,pl_content) values (59,'测试内容3')
select Test_001.*,Test_002.* from Test_001,Test_002 where Test_001.p_id=Test_002.pl_id
结果
id p_id p_name id pl_id pl_content
1 57 测试标题1 1 57 测试内容1
2 57 测试标题2 1 57 测试内容1
3 57 测试标题3 1 57 测试内容1
------解决方案--------------------看看这个是不是你想要的:
select * from p_news left join
(select * from pinglun,
(select min(id) as f1, pinglun_ID as f2 from pinglun group by pinglun_ID) as t1
where pinglun.id=t1.f1) as t2
on p_news.p_news_id=t2.f2