jaggedsoft
jaggedsoft

Reputation: 4038

How to combine three MySQL queries into one?

Using a wordpress database we have tables like wp_options, and wp_postmeta. These are grouped by primary key ID, then fields like 'option_name' and 'option_value';

So for example to find out three values I'd need to do 3 different queries.

Is there a proper way to do all of this with only one query?

Please shed some light on this and share the right way to do this.

SELECT option_value FROM bdlocal_wrdp1.wp_options WHERE option_name='siteurl';

SELECT option_value FROM bdlocal_wrdp1.wp_options WHERE option_name='blogname';

SELECT option_value FROM bdlocal_wrdp1.wp_options WHERE option_name='blogdescription';

(returns example.com, Example Blog, This is an example blog.)

Upvotes: 3

Views: 142

Answers (4)

jaggedsoft
jaggedsoft

Reputation: 4038

You can also use a MySQL Union for this functionality:

select option_name,option_value from wp_options where option_name='siteurl' UNION ALL
select option_name,option_value from wp_options where option_name='blogname' UNION ALL
select option_name,option_value from wp_options where option_name='blogdescription';

You can read more about Unions with some examples here.

Upvotes: 0

Vikram Jain
Vikram Jain

Reputation: 5588

select (case when option_name='siteurl' then option_value else 0 end ) as 'siteurl',
   (case when option_name='blogname' then option_value else 0 end ) as 'blogname',
   (case when option_name='blogdescription' then option_value else 0 end ) as 'blogdescription' from bdlocal_wrdp1.wp_options

Upvotes: 1

John Woo
John Woo

Reputation: 263693

You can you IN clause for this,

SELECT option_value 
FROM bdlocal_wrdp1.wp_options 
WHERE option_name IN ('siteurl','blogname','blogdescription')

Upvotes: 3

zerkms
zerkms

Reputation: 254886

SELECT option_name,
       option_value
  FROM bdlocal_wrdp1.wp_options
 WHERE option_name IN ('siteurl', 'blogname', 'blogdescription')

And after this query execution you'll have 3 pairs of option_name + option_value values.

Upvotes: 7

Related Questions