mysql查詢(xún)語(yǔ)句中distinct的問(wèn)題
mysql查詢(xún)語(yǔ)句我們都經(jīng)常在用,今天維護(hù)數(shù)據(jù)庫(kù)出現(xiàn)以下需求,mysql查詢(xún)語(yǔ)句查出user表中不重復(fù)的記錄,使用distinct但他只能對(duì)一個(gè)字段有效,我試了好多次不行,怎么辦呢?
原因就是 distinct它來(lái)返回不重復(fù)記錄的條數(shù),而不是用它來(lái)返回不重記錄的所有值。
也就是distinct只能返回它的目標(biāo)字段,而無(wú)法返回其它字段
例如:
- SELECT DISTINCT mac,ip from ip
- +------+------+
- | mac | ip |
- +------+------+
- | abc | 678 |
- | abc | 123 |
- | def | 456 |
- | abc | 12 |
- +------+------+
他還是不會(huì)有變換!因?yàn)樯厦娴恼Z(yǔ)句產(chǎn)生的作用就是作用了兩個(gè)字段,也就是必須得mac與ip都相同的才會(huì)被排除
***沒(méi)有辦法,使用group by 看看!!!!
查看mysql 手冊(cè)!connt(distinct name) 可以配合group by 實(shí)現(xiàn)。
一個(gè)count函數(shù)實(shí)現(xiàn)我要的功能。
- select *,count(distinct mac) from ip group by mac;
- +------+------+---------------------+
- | mac | ip | count(distinct mac) |
- +------+------+---------------------+
- | abc | 678 | 1 |
- | def | 456 | 1 |
- +------+------+---------------------+
基本實(shí)現(xiàn)我的想法!
那如何實(shí)現(xiàn)一個(gè)表有兩個(gè)字段mac和ip,如何找出所有的mac相同而ip不同的記錄?
- mysql> select * from ip;
- +-----+-----+
- | mac | ip |
- +-----+-----+
- | abc | 123 |
- | def | 456 |
- | ghi | 245 |
- | abc | 678 |
- | def | 864 |
- | abc | 123 |
- | ghi | 245 |
- +-----+-----+
- 7 rows in set (0.00 sec)
- mysql> SELECT DISTINCT a.mac, a.ip
- -> FROM ip a, ip b
- -> WHERE a.mac = b.mac AND a.ip <> b.ip ORDER BY a.mac;
- +-----+-----+
- | mac | ip |
- +-----+-----+
- | abc | 678 |
- | abc | 123 |
- | def | 864 |
- | def | 456 |
- +-----+-----+
- 4 rows in set (0.00 sec)
【編輯推薦】
教您如何實(shí)現(xiàn)MySQL全文查詢(xún)