百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>数据库> 多表查询去除重复记录
分享文章到:

多表查询去除重复记录

发布时间:01/15 来源: 浏览: 关键词:

多表查询去除重复记录

首先关于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

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有5人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板