mysql查詢語句中distinct的問題
mysql查詢語句我們都經常在用,今天維護數(shù)據(jù)庫出現(xiàn)以下需求,mysql查詢語句查出user表中不重復的記錄,使用distinct但他只能對一個字段有效,我試了好多次不行,怎么辦呢?
原因就是 distinct它來返回不重復記錄的條數(shù),而不是用它來返回不重記錄的所有值。
也就是distinct只能返回它的目標字段,而無法返回其它字段
例如:
- SELECT DISTINCT mac,ip from ip
- +------+------+
- | mac | ip |
- +------+------+
- | abc | 678 |
- | abc | 123 |
- | def | 456 |
- | abc | 12 |
- +------+------+
他還是不會有變換!因為上面的語句產生的作用就是作用了兩個字段,也就是必須得mac與ip都相同的才會被排除
***沒有辦法,使用group by 看看?。。?!
查看mysql 手冊!connt(distinct name) 可以配合group by 實現(xiàn)。
一個count函數(shù)實現(xiàn)我要的功能。
- select *,count(distinct mac) from ip group by mac;
- +------+------+---------------------+
- | mac | ip | count(distinct mac) |
- +------+------+---------------------+
- | abc | 678 | 1 |
- | def | 456 | 1 |
- +------+------+---------------------+
基本實現(xiàn)我的想法!
那如何實現(xiàn)一個表有兩個字段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)
【編輯推薦】