Recipe 3.5. Combining Columns to Construct Composite Values


Problem

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

Solution

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

Discussion

Column values can 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, but you can use column aliases to provide better ones. The following statement 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, 2006 | barb@saturn   | tricia@mars   |   58274 | | May 12, 2006 | tricia@mars   | gene@venus    |  194925 | | May 12, 2006 | phil@mars     | phil@saturn   |    1048 | | May 13, 2006 | barb@saturn   | tricia@venus  |     271 | ... 




MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2004
Pages: 375
Authors: Paul DuBois

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