WordPress's wp_postmeta table has all the additional fields for a post but they are in rows so it's easy to add more.
However, now I want to query for all the fields of all the posts lets say, I obviously want those fields in a column and not a row.
This is my query that I am running
SELECT p.post_title,
m.meta_value,
m.meta_key
FROM wp_posts p
JOIN wp_postmeta m
ON p.id = m.post_id
WHERE p.id = 72697;
This will give me all the meta_values and their respective meta keys as columns. But I need the meta keys values as columns and meta values as rows
For example a meta_key could be additional_description and it's value could be What's up
So I need something like this
SELECT p.post_title, additional_description
FROM wp_posts p
JOIN wp_postmeta m
ON p.id = m.post_id
WHERE p.id = 72697;
I need it as a column. I also need all of the posts and not a specific one, but whenever I remove the where it just doesn't query (I have lots of posts, that could be an issue).
Here is some sample data and how I want the results to show up
wp_postmeta table
meta_key post_id meta_key meta_value
1 5 total_related 5
2 5 updated 0
3 5 cricket 1
4 8 total_related 8
5 8 updated 1
6 8 cricket 0
wp_post table
id post_title other things I dont care about
5 This is awesome
8 This is more awesome
wp_post id is related to post_id on wp_postmeta table
Result wanted
post_title total_related updated cricket
This is awesome 5 0 1
This is more awesome 8 1 0
What about something like this?
SELECT p.post_title, m1.meta_value as 'total_related', m2.meta_value as 'updated', m3.meta_value as 'cricket'
FROM wp_posts p
LEFT JOIN wp_postmeta m1
ON p.id = m1.post_id AND m1.meta_key = 'total_related'
LEFT JOIN wp_postmeta m2
ON p.id = m2.post_id AND m2.meta_key = 'updated'
LEFT JOIN wp_postmeta m3
ON p.id = m3.post_id AND m3.meta_key = 'cricket'
And since you aren't looking for a specific post you should be able to do this.
If you want to query specific post_types you can try something like this
SELECT p.post_title, m1.meta_value as 'total_related', m2.meta_value as 'updated', m3.meta_value as 'cricket'
FROM wp_posts p
LEFT JOIN wp_postmeta m1
ON p.id = m1.post_id AND m1.meta_key = 'total_related'
LEFT JOIN wp_postmeta m2
ON p.id = m2.post_id AND m2.meta_key = 'updated'
LEFT JOIN wp_postmeta m3
ON p.id = m3.post_id AND m3.meta_key = 'cricket'
WHERE p.post_type = 'my_custom_post_type';
Try that:
select post_title ,
MAX(CASE WHEN `meta_key`='total_related' THEN meta_value END)as 'total_related',
MAX(CASE WHEN `meta_key` = 'updated' THEN meta_value END) as 'updated' ,
MAX(CASE WHEN `meta_key` = 'cricket' THEN meta_value END) as 'cricket'
FROM wp_posts p
JOIN wp_postmeta m ON p.id = m.post_id
GROUP BY p.id
There are several approaches.
Here's an example of one way to get the specified result, using correlated subqueries in the SELECT list:
SELECT p.post_title
, ( SELECT m1.meta_value
FROM wp_post_metadata m1
WHERE m1.meta_key = 'total_related'
AND m1.post_id = p.id
ORDER BY m1.meta_key LIMIT 1
) AS `total_related`
, ( SELECT m2.meta_value
FROM wp_post_metadata m2
WHERE m2.meta_key = 'updated'
AND m2.post_id = p.id
ORDER BY m2.meta_key LIMIT 1
) AS `updated`
, ( SELECT m3.meta_value
FROM wp_post_metadata m3
WHERE m3.meta_key = 'cricket'
AND m3.post_id = p.id
ORDER BY m3.meta_key LIMIT 1
) AS `cricket`
FROM wp_posts p
WHERE p.id IN (5,8)
There are several other approaches, each with its own advantages and drawbacks.
There's a somewhat related question I referenced in a comment on the question. That question illustrates several approaches, but omits a correlated subquery approach.)
Here's how I did this dynamically - this procedure builds a SQL statement for every postmeta key for a given post type and then runs the "pivot" query for you:
This isn't the fastest query, and we use it only for migration and deep dives into data, but it does the job.
Note that this temporarily resets the max length of the concat function so you can build a large SQL statement:
CREATE PROCEDURE `wp_posts_pivot`(IN post_type_filter varchar(50))
BEGIN
/* allow longer concat */
declare max_len_original INT default 0;
set max_len_original = ##group_concat_max_len;
set ##group_concat_max_len=100000;
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(pm.meta_key = ''',
meta_key,
''', pm.meta_value, NULL)) AS `',
meta_key,
'`'))
INTO #sql FROM
wp_posts p
INNER JOIN
wp_postmeta AS pm ON p.id = pm.post_id
WHERE
p.post_type = post_type_filter;
SET #sql = CONCAT('SELECT p.id
, p.post_title
, ', #sql, '
FROM wp_posts p
LEFT JOIN wp_postmeta AS pm
ON p.id = pm.post_id
where p.post_type=\'',post_type_filter,'\'
GROUP BY p.id, p.post_title');
/* reset the default concat */
set ##group_concat_max_len= max_len_original;
/*
select #sql;
*/
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
You can then call this with a simple call such as this one, which will select a single row for each 'page' post type along with all meta values:
call wp_posts_pivot('page');
Related
I had problem during importing products. And now some of the products are duplicated. All of the duplicated products have the same title and attribute (collection_id). Also there are a lot of duplicated media files. Is there a way to remove duplicated products? At least i want to remove products.
I had the same problem and it was I did.
1.- In my database found duplicated products (searching by sku) with the query:
SELECT meta_value, count(*) AS total FROM wp_postmeta WHERE meta_key = '_sku' GROUP BY meta_value HAVING total > 1
2.- I create a new table called wp_repeated with these skus:
CREATE TABLE wp_repeated AS SELECT meta_value, count(*) AS total FROM wp_postmeta WHERE meta_key = '_sku' GROUP BY meta_value HAVING total > 1
3.- I got the post_id from these skus:
SELECT p.ID FROM `wp_posts` as p INNER JOIN wp_postmeta as m on p.ID = m.post_id WHERE p.post_type IN ('product','product_variation') AND m.meta_key = '_sku' AND m.meta_value in (select meta_value from wp_repeated)
4.- And, finally, remove and delete from all tables where the post_id appears:
DELETE relations.*, taxes.*, terms.* FROM wp_term_relationships AS relations INNER JOIN wp_term_taxonomy AS taxes ON relations.term_taxonomy_id=taxes.term_taxonomy_id INNER JOIN wp_terms AS terms ON taxes.term_id=terms.term_id WHERE object_id IN (SELECT p.ID FROM `wp_posts` as p INNER JOIN wp_postmeta as m on p.ID = m.post_id WHERE p.post_type IN ('product','product_variation') AND m.meta_key = '_sku' AND m.meta_value in (select meta_value from wp_repeated)); DELETE FROM wp_postmeta WHERE post_id IN ( SELECT p.ID FROM `wp_posts` as p INNER JOIN wp_postmeta as m on p.ID = m.post_id WHERE p.post_type IN ('product','product_variation') AND m.meta_key = '_sku' AND m.meta_value in (select meta_value from wp_repeated)); DELETE FROM wp_posts WHERE ID IN (SELECT p.ID FROM `wp_posts` as p INNER JOIN wp_postmeta as m on p.ID = m.post_id WHERE p.post_type IN ('product','product_variation') AND m.meta_key = '_sku' AND m.meta_value in (select meta_value from wp_repeated));
I hope it can be helpful to you. Regards.
TAKE CARE: these queries remove ALL repeated products.
I have a query that connects to a wordpress db and returns some posts.
In order to get the image for each of these posts i run another query inside a php foreach loop
The problem is that running the second query inside the foreach loop is extremely slow and i need another way to merge these 2 queries into 1.
The first query
SELECT pm. * , p.*
FROM wp_posts p
JOIN wp_postmeta pm ON pm.post_id = p.ID
WHERE pm.meta_key = 'accommodation_location_post_id'
AND pm.meta_value
IN (
SELECT pi.ID
FROM wp_posts pi
WHERE pi.post_title LIKE '%Cyprus%')
Based on the returned post ids, i need for each of these ids
the featured image.
This query does this job, but only for 1 id only.
The second query
SELECT wp_posts.guid
FROM wp_posts
WHERE wp_posts.ID =
(Select wp_postmeta.meta_value
FROM wp_postmeta
WHERE wp_postmeta.meta_key =
'_thumbnail_id' AND wp_postmeta.post_id = 'The id of each post')
I need a query to return all the posts alongside with its images.
I really don't understand your data structure, but try this query
select
t1.*, t2.guid
from (
SELECT pm. * , p.*
FROM wp_posts p
JOIN wp_postmeta pm ON pm.post_id = p.ID
WHERE pm.meta_key = 'accommodation_location_post_id'
AND pm.meta_value IN (
SELECT pi.ID
FROM wp_posts pi
WHERE pi.post_title LIKE '%Cyprus%'
)
) t1
left join (
select
p2.guid, pm2.post_id
from
wp_posts p2
join wp_postmeta pm2 on
pm2.meta_value = p2.ID
and pm2.meta_key = '_thumbnail_id'
) t2 on t2.post_id = t1.ID
I have a mysql issues.
I have this select
SELECT DISTINCT t2.meta_key,t2.meta_value
FROM wp_woocommerce_order_items AS t1
JOIN wp_woocommerce_order_itemmeta AS t2 ON t1.order_item_id = t2.order_item_id
JOIN wp_posts as t3 ON t3.ID=t1.order_id
WHERE t2.order_item_id IN(SELECT distinct t1.order_item_id FROM wp_woocommerce_order_items AS t1
JOIN wp_woocommerce_order_itemmeta AS t2 ON t1.order_item_id = t2.order_item_id WHERE t2.meta_key like "_product_id" AND t2.meta_value = 99) AND t2.meta_key="member_id" AND t3.post_status like "publish"
this Select query get all "member_id"(meta_key) where the "_product_id" equals 99.
I hav3 a good result. it's maybe not "elegant" but it's works.
My problem now, I need to get all member_id where the _product_id equal 99 AND
the Order is not cancelled.
Also, I don't know which table and what is the real key that "order_status" are.
So,
Thanks For you help!
EDIT
I added the
JOIN wp_posts as t3 ON t3.ID=t1.order_id
and
WHERE t3.post_status = "publish"
The current value that I need is in the table: wp_term.
thanks
ok, I got it.
This query take all "meta_value" (here: member_id)
On all orders where
Order status is not : "failed' 'cancelled' or 'refunded'
where order have the product id is 99
Where the order is not into the trash.
so :
SELECT t2.meta_value
FROM wp_woocommerce_order_items AS t1
JOIN wp_woocommerce_order_itemmeta AS t2 ON t1.order_item_id = t2.order_item_id
WHERE t2.order_item_id IN(SELECT DISTINCT oi.order_item_id
FROM wp_posts, wp_postmeta, wp_term_relationships tr,wp_term_taxonomy tt,
wp_terms te, wp_woocommerce_order_itemmeta oi, wp_woocommerce_order_items ii
WHERE tt.taxonomy like "shop_order_status"
AND te.term_id = tt.term_id
AND te.slug NOT IN ('failed','cancelled','refunded')
AND tr.term_taxonomy_id = tt.term_taxonomy_id
AND oi.order_item_id = ii.order_item_id
AND oi.meta_key = '_product_id'
AND oi.meta_value = 99
AND ii.order_id = wp_posts.ID
AND wp_postmeta.post_id = tr.object_id
AND wp_posts.post_status = 'publish') AND t2.meta_key like "member_id"
I hope to help someOne.
If you have more elegant or more optimisation of this query.
Feel free to tell us :-)
I've spent most of my day trying to figure this out so I guess it's time I ask the experts:
I'm trying to access my WordPress DB outside of WordPress, so I'm writing queries to get output from the somewhat complicated WordPress database.
There are several tables in the DB that use meta_values and meta_keys to store data about a post or user in multiple rows.
For Example here are four tables I need to pull from:
table: wp_postmeta
post_id | meta_key | meta_value
---------+-----------------+------------
2001 | _customer_user | 3
2001 |order_description| smith
2001 | _order_total | 300
table: wp_posts
ID | post_type | post_status
----+-----------+------------
2001| shop_order| publish
table: wp_term_relationships
object_id | term_taxonomy_id
----------+-----------------
2001 | 190
table: wp_usermeta
user_id | meta_key |meta_value
---------+-----------------+----------
3 | first_name | Andy
3 | last_name | Mccormick
I've got this query to work great to display the Order Number (post_id) Customer ID, Order Description, and Order total in a single row:
SELECT wp_posts.ID, wp_posts.post_title,ot.meta_value as total,od.meta_value as order_desc, cu.meta_value as customer
FROM wp_posts
LEFT JOIN wp_postmeta AS ot ON (wp_posts.ID = ot.post_id AND ot.meta_key='_order_total')
LEFT JOIN wp_postmeta AS od ON (wp_posts.ID = od.post_id AND od.meta_key='order_description')
LEFT JOIN wp_postmeta AS cu ON (wp_posts.ID =cu.post_id AND cu.meta_key='_customer_user')
LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
WHERE wp_posts.post_type = 'shop_order'
AND wp_posts.post_status = 'publish'
AND wp_term_relationships.term_taxonomy_id = '190'
GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC"
However in another area I want to list the customers by name and not just by ID so I'm trying to get their first and last name from the wp_usermeta table like this:
SELECT wp_posts.ID, cu.meta_value as customer, fn.meta_vale as fname, ln.meta_value as lname
FROM wp_posts
LEFT JOIN wp_postmeta AS cu ON (wp_posts.ID = cu.post_id AND cu.meta_key='_customer_user')
LEFT JOIN wp_usermeta AS fn ON (cu.meta_key = fn.user_id AND fn.meta_key='first_name')
LEFT JOIN wp_usermeta AS ln ON (cu.meta_key = ln.user_id AND ln.meta_key='last_name')
LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
WHERE wp_posts.post_type = 'shop_order'
AND wp_posts.post_status = 'publish'
AND wp_term_relationships.term_taxonomy_id = '190'
GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC;
I've also tried:
LEFT JOIN wp_usermeta AS fn ON ((cu.meta_key='_customer_user') = fn.user_id AND fn.meta_key='first_name') along with a host of other subqueries and such.
Obviously I'm above my pay-grade in SQL queries right now so any help would be great. thanks!
I'm not sure, but you might try this:
SELECT wp_posts.ID, cu.meta_value as customer, fn.meta_vale as fname, ln.meta_value as lname
FROM wp_posts
LEFT JOIN wp_postmeta AS cu ON (wp_posts.ID = cu.post_id AND cu.meta_key='_customer_user')
LEFT JOIN wp_usermeta AS fn ON (cu.meta_value = fn.user_id AND fn.meta_key='first_name') // Note meta_value instead of meta_key
LEFT JOIN wp_usermeta AS ln ON (cu.meta_value = ln.user_id AND ln.meta_key='last_name') // Note meta_value instead of meta_key
LEFT JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
WHERE wp_posts.post_type = 'shop_order'
AND wp_posts.post_status = 'publish'
AND wp_term_relationships.term_taxonomy_id = '190'
GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC;
From what I've figured out, cu.meta_value is 3 in your example as it's the user's id, while cu.meta_key (as in your query) is '_customer_id', so you rather want to match cu.meta_value than cu.meta_key. Couldn't check though, as I have no WP installation laying around.
I have a sample data
product (ID, name)
1 | 'iPhone'
2 | 'iPad'
3 | 'iWatch'
product_meta (ID, product_id, meta_key, meta_value)
1 1 image iPhone.png
2 2 view 123
And using query:
SELECT p.*, m.*
FROM product AS p
LEFT JOIN product_meta AS m ON m.product_id = p.ID
WHERE p.ID = 1
GROUP BY p.ID
How to get all value to result is
product(ID, name, image, view) => 1 | iPhone | iPhone.png | 123
Assuming your sample data is incorrect and you're trying to PIVOT your results, you can use MAX with CASE for this:
select p.id,
p.name,
max(case when pm.meta_key = 'image' then pm.meta_value end) image,
max(case when pm.meta_key = 'view' then pm.meta_value end) view
from product AS p
left join product_meta AS pm ON pm.product_id = p.ID
where p.ID = 1
group by p.ID
you can do like select table1.column1, table2.column2 from .......... rest of query.
Based on the same assumption as sgeddes:
SELECT p.id, p.name, mimage.meta_value, mview.meta_value
FROM product AS p
LEFT JOIN product_meta AS mimage
ON mimage.product_id = p.id AND mimage.meta_key = 'image'
LEFT JOIN product_meta AS mview
ON mview.product_id = p.id AND mview.meta_key = 'view'
WHERE p.id = 1