Displaying Comparisons to Find Out How Something Works

3.9.1 Problem

You're curious about how a comparison in a WHERE clause works. Or perhaps about why it doesn't seem to be working.

3.9.2 Solution

Display the result of the comparison to get more information about it. This is a useful diagnostic or debugging technique.

3.9.3 Discussion

Normally you put comparison operations in the WHERE clause of a query and use them to determine which records to display:

mysql> SELECT * FROM mail WHERE srcuser < 'c' AND size > 5000;
+---------------------+---------+---------+---------+---------+-------+
| t | srcuser | srchost | dstuser | dsthost | size |
+---------------------+---------+---------+---------+---------+-------+
| 2001-05-11 10:15:08 | barb | saturn | tricia | mars | 58274 |
| 2001-05-14 14:42:21 | barb | venus | barb | venus | 98151 |
+---------------------+---------+---------+---------+---------+-------+

But sometimes it's desirable to see the result of the comparison itself (for example, if you're not sure that the comparison is working the way you expect it to). To do this, just put the comparison expression in the output column list, perhaps including the values that you're comparing as well:

mysql> SELECT srcuser, srcuser < 'c', size, size > 5000 FROM mail;
+---------+---------------+---------+-------------+
| srcuser | srcuser < 'c' | size | size > 5000 |
+---------+---------------+---------+-------------+
| barb | 1 | 58274 | 1 |
| tricia | 0 | 194925 | 1 |
| phil | 0 | 1048 | 0 |
| barb | 1 | 271 | 0 |
...

This technique of displaying comparison results is particularly useful for writing queries that check how a test works without using a table:

mysql> SELECT 'a' = 'A';
+-----------+
| 'a' = 'A' |
+-----------+
| 1 |
+-----------+

This query result tells you that string comparisons are not by default case sensitive, which is a useful thing to know.

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