Can you use the result of a SQL query inside another SQL query in the same statement?

Posted on 2009-02-22
Medium Priority
Last Modified: 2013-12-26
I am writing a bash script to backup some information. I am currently a MySQL novice, but I figured out that I can find location(s) of this information by doing 2 SQL queries like:
"SELECT id FROM domains where name='$SITE' limit 1"
I then take the result of that ($DOMID) and use it in the other query like:
"SELECT name FROM data_bases where dom_id=$DOMID"

My question is can I combine the 2 queries to basically do something like:
"SELECT name FROM data_bases where dom_id=(SELECT id FROM domains where name='$SITE' limit 1)"

I am calling these from a bash script like:
mysql -usuer -ppassword -Ddatabase -e "SELECT ..."
So a related question would be, is there also a way to suppress the column labels and/or ASCII boxes around the output, so my parsing of the output would be easier?
Question by:GuruGary
LVL 143

Accepted Solution

Guy Hengel [angelIII / a3] earned 2000 total points
ID: 23708661
you can do it like this:
"SELECT db.name FROM data_bases db JOIN domains d ON db.dom_id= d.id where d.name='$SITE'"

Open in new window

LVL 10

Author Closing Comment

ID: 31549961
That works great, thanks!  And I figured out how to suppress the column headers (mysql switch "--skip-column-names") and the ASCII boxes (mysql switch "-s")

Featured Post

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Utilizing an array to gracefully append to a list of EmailAddresses
When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses
Course of the Month14 days, 23 hours left to enroll

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question