设为首页 加入收藏

TOP

多表查询去除重复记录
2011-06-12 21:31:36 来源: 作者: 【 】 浏览:50次 评论:0

多表查询去除重复记录

首先关于sql  多表查询去除重复记录我们就可以想到用group by 或distinct 再着想到inner left 等,
下面来看看个实例

看一个distinct 实例

现在将完整语句放出:

select *, count(distinct name) from table group by name

结果:

   id name count(distinct name)
   1 a 1
   2 b 1
   3 c 1

最后一项是多余的,不用管就行了,目的达到。。。。。

group by 必须放在 order by 和 limit之前,不然会报错

db_a:
id    age
1      20
2       30
3      40
4       50
db_b:
topid      poto
  2           axxxxxxxxxx
  2           bxxxxxxxxxx
  2           cxxxxxxxxxxx
  3           dxxxxxxxxxxx

SELECT * FROM db_a AS A LEFT JOIN db_b AS B ON B.topid=A.id;

现在查询出来有6条数据, 怎么解决.

SELECT * FROM db_a AS A RIGHT JOIN db_b AS B ON B.topid=A.id;
//四条数据。是你要的吗
id  age  topicid  poto 
2 bbbbbb 2 axxxxx
2 bbbbbb 2 bxxxxxx
2 bbbbbb 2 cxxxxx
3 cccccc 3 dxxxxxx

SELECT * FROM db_a AS A, db_b AS B WHERE B.topid = A.id

select distinct(列名) from 表
找出这个表中,这个列里,不重复的值出来
distinct(列名)

SELECT * FROM db_a AS A INNER JOIN db_b AS B ON A.id = B.topid;

SELECT * FROM db_a AS A left JOIN db_b AS B ON A.id = B.topid goup by a.id;

另外更多方法


方法一:用union

select a.menuId, menuAliasNumber, menuName1, menuName2 ,
(select price from workmenuPrice where workmenuPrice.menuId=a.menuId and menuPriceTypeId=1) as 'reg',
(select price from workmenuPrice where workmenuPrice.menuId=a.menuId and menuPriceTypeId=2) as 'large',
(select price from workmenuPrice where workmenuPrice.menuId=a.menuId and menuPriceTypeId=3) as 'small'
from workmenuItems a right join workmenuCatUse b on a.menuId=b.menuId
right join workmenuPrice c on c.menuId=b.menuId
union
select a.menuId, menuAliasNumber, menuName1, menuName2 ,
(select price from workmenuPrice where workmenuPrice.menuId=a.menuId and menuPriceTypeId=1) as 'reg',
(select price from workmenuPrice where workmenuPrice.menuId=a.menuId and menuPriceTypeId=2) as 'large',
(select price from workmenuPrice where workmenuPrice.menuId=a.menuId and menuPriceTypeId=3) as 'small'
from workmenuItems a right join workmenuCatUse b on a.menuId=b.menuId
right join workmenuPrice c on c.menuId=b.menuId

方法二:用distinct

select distinct(a.menuId), menuAliasNumber, menuName1, menuName2 ,
(select price from workmenuPrice where workmenuPrice.menuId=a.menuId and menuPriceTypeId=1) as 'reg',
(select price from workmenuPrice where workmenuPrice.menuId=a.menuId and menuPriceTypeId=2) as 'large',
(select price from workmenuPrice where workmenuPrice.menuId=a.menuId and menuPriceTypeId=3) as 'small'
from workmenuItems a right join workmenuCatUse b on a.menuId=b.menuId
right join workmenuPrice c on c.menuId=b.menuId

您看到此篇文章时的感受是:
Tags: 责任编辑:administrator
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到QQ空间
分享到: 
上一篇解决PHP存取MySQL 4.1乱码问题 下一篇mysql sql 防止重复插入相同的记..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

相关栏目

最新文章

图片主题

热门文章

推荐文章

相关文章

广告位