Combining Columns to Construct Composite Values

3.6.1 Problem

You want to display values that are constructed from multiple table columns.

3.6.2 Solution

One way to do this is to use CONCAT( ). You might also want to give the column a nicer name by using an alias.

3.6.3 Discussion

Column values may be combined to produce composite output values. For example, this expression concatenates srcuser and srchost values into email address format:

CONCAT(srcuser,'@',srchost)

Such expressions tend to produce ugly column names, which is yet another reason why column aliases are useful. The following query uses the aliases sender and recipient to name output columns that are constructed by combining usernames and hostnames into email addresses:

mysql> SELECT
 -> DATE_FORMAT(t,'%M %e, %Y') AS date_sent,
 -> CONCAT(srcuser,'@',srchost) AS sender,
 -> CONCAT(dstuser,'@',dsthost) AS recipient,
 -> size FROM mail;
+--------------+---------------+---------------+---------+
| date_sent | sender | recipient | size |
+--------------+---------------+---------------+---------+
| May 11, 2001 | barb@saturn | tricia@mars | 58274 |
| May 12, 2001 | tricia@mars | gene@venus | 194925 |
| May 12, 2001 | phil@mars | phil@saturn | 1048 |
| May 13, 2001 | barb@saturn | tricia@venus | 271 |
...

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