MySQL: Use CONCAT to include text in SELECT results

Home -> Database -> MySQL

15171 views

From the computer of: qmchenry (338 recipes)
Created: Jan 31, 2007     Updated: Feb 05, 2007


Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL

The CONCAT function in MySQL allows SELECT statements to act like printf commands by mingling text and query results together.

For example, to generate a quick list of links in HTML from a table 'links' with the columns 'url' (http://www.tech-recipes.com) and 'title' (Tech-Recipes) so that the output looks like:

<a href="http://www.tech-recipes.com">Tech-Recipes</a><br />


use a select statement like:

SELECT CONCAT('<a href="', url, '">', title, '</a><br />') FROM links;


The CONCAT function simply joins the comma-separated list of strings and expressions (in this case column results from the query: url and title). As with any SELECT statement, the result set can be varied with the use of an optional WHERE clause and other valid SQL syntax.

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.





Related recipes:

  Save MySQL query results into a text or CSV file
  Connect to a MySQL server using the mysql command
  Display a list of databases on a MySQL server
  Solve: Can't connect to local MySQL server through socket /tmp/mysql.sock
  Determine the version of MySQL server
  Select a MySQL database to use
  Describe the column structure of a MySQL table
  Create a MySQL database
  Drop or delete a table in MySQL
  Use regular expressions in MySQL SELECT statements

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.