Determining Whether Values are Unique

7.11.1 Problem

You want to know whether table values are unique.

7.11.2 Solution

Use HAVING in conjunction with COUNT( ).

7.11.3 Discussion

You can use HAVING to find unique values in situations to which DISTINCT does not apply. DISTINCT eliminates duplicates, but doesn't show which values actually were duplicated in the original data. HAVING can tell you which values were unique or non-unique.

The following queries show the days on which only one driver was active, and the days on which more than one driver was active. They're based on using HAVING and COUNT( ) to determine which trav_date values are unique or non-unique:

mysql> SELECT trav_date, COUNT(trav_date)
 -> FROM driver_log
 -> GROUP BY trav_date
 -> HAVING COUNT(trav_date) = 1;
+------------+------------------+
| trav_date | COUNT(trav_date) |
+------------+------------------+
| 2001-11-26 | 1 |
| 2001-11-27 | 1 |
| 2001-12-01 | 1 |
+------------+------------------+
mysql> SELECT trav_date, COUNT(trav_date)
 -> FROM driver_log
 -> GROUP BY trav_date
 -> HAVING COUNT(trav_date) > 1;
+------------+------------------+
| trav_date | COUNT(trav_date) |
+------------+------------------+
| 2001-11-29 | 3 |
| 2001-11-30 | 2 |
| 2001-12-02 | 2 |
+------------+------------------+

This technique works for combinations of values, too. For example, to find message sender/recipient pairs between whom only one message was sent, look for combinations that occur only once in the mail table:

mysql> SELECT srcuser, dstuser
 -> FROM mail
 -> GROUP BY srcuser, dstuser
 -> HAVING COUNT(*) = 1;
+---------+---------+
| srcuser | dstuser |
+---------+---------+
| barb | barb |
| gene | tricia |
| phil | barb |
| tricia | gene |
| tricia | phil |
+---------+---------+

Note that this query doesn't print the count. The first two examples did so, to show that the counts were being used properly, but you can use a count in a HAVING clause without including it in the output column list.

Using the mysql Client Program

Writing MySQL-Based Programs

Record Selection Techniques

Working with Strings

Working with Dates and Times

Sorting Query Results

Generating Summaries

Modifying Tables with ALTER TABLE

Obtaining and Using Metadata

Importing and Exporting Data

Generating and Using Sequences

Using Multiple Tables

Statistical Techniques

Handling Duplicates

Performing Transactions

Introduction to MySQL on the Web

Incorporating Query Resultsinto Web Pages

Processing Web Input with MySQL

Using MySQL-Based Web Session Management

Appendix A. Obtaining MySQL Software

Appendix B. JSP and Tomcat Primer

Appendix C. References



MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2005
Pages: 412
Authors: Paul DuBois

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net