I'm trying to figure it ou a way to make this selects in the same query. I'm working on the wordpress database, and I have these SQL queries that works by themselves:
SELECT `meta_value` AS 'Name' FROM `wp_postmeta` WHERE `meta_key` = "myfield1" ORDER BY `post_id` ASC
SELECT `meta_value` AS 'Department' FROM `wp_postmeta` WHERE `meta_key` = "myfield2" ORDER BY `post_id` ASC
SELECT `meta_value` AS 'Location' FROM `wp_postmeta` WHERE `meta_key` = "myfield3" ORDER BY `post_id` ASC
SELECT `meta_value` AS 'Job Title' FROM `wp_postmeta` WHERE `meta_key` = "myfield4" ORDER BY `post_id` ASC
SELECT `meta_value` AS 'Social Number' FROM `wp_postmeta` WHERE `meta_key` = "myfield5" ORDER BY `post_id` ASC
But I'd like to have them all on the same query so I can export the data later on a report. Here's what I've tried:
SELECT
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield1" ORDER BY `post_id` ASC) As name,
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield2" ORDER BY `post_id` ASC) AS department,
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield3" ORDER BY `post_id` ASC) AS location,
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield4" ORDER BY `post_id` ASC) AS jobtitle,
(SELECT `meta_value` FROM `wp_postmeta` WHERE `meta_key` = "myfield5" ORDER BY `post_id` ASC) AS socnumber
But that's returning commands out of sync. Anyone knows how to fix this?
#2014 - Commands out of sync; you can't run this command now
Edit: I'm querying the wp_postmeta table, it has 4 columns meta_id, post_id, meta_key and meta_value columns. I'm selecting the meta_value from a custom field I've added (called myfield1, saved in the meta_key column). I'm ordering by post_id which is the ID of the posts in wordpress so I get chronologic order.
But I have 5 custom fields, myfield1 to myfield5. And I wanted to query all of them once.
To get a resultset with five columns (one for each custom field) you have to join the table to itself five times...
Something like this:
I haven't checked the SQL syntax, so forgive me if there's a syntax error!
Assuming this is mySQL?
One method is to use conditional aggregation:
You can't select the same column with as different alias (`'meta_value' AS 'Name' ... etc) and get the results as one set. The column can only have one name!
The best you can do is something like this:
Which will give you all your values in one result set, with the
meta_key
column too so you can tell which is which.