I'm trying to write a mysql query and I'm having some issues with it. I'm trying to query WooCommerce data out of my Wordpress database. Basic invoice data is stored in the wp_posts table and the rest of the data is stored in the wp_postmeta table. Now 1 inovice in the wp_posts table points to multiple items in the wp_postmeta table. Here is an example.
WP_POSTS
---------------------------------------------------- ID STATUS Date ---------------------------------------------------- 0001 OPEN 01/01/2000 0002 OPEN 01/01/2000 0003 CLOSED 01/02/2000
WP_POSTMETA
-------------------------------------------------------------------------- ID POST_ID META_KEY META_VALUE -------------------------------------------------------------------------- 0001 0001 CustomerLN Test 0002 0001 CustomerFN Tester 0003 0001 Payment_Type PayPal 0004 0001 Invoice_Total $200 0005 0002 CustomerLN Doe 0006 0002 CustomerFN John 0007 0002 Payment_Type CC-Mastercard 0008 0002 Invoice_Total $1000
I've got a basic query that pulls the data in from the wp_posts table but I can't figure out how to pull data from the second table based on the META_KEY value.
Any help would be great. Thanks in advance.
Welcome to the Entity-Attribute-Value world.
To have a normal representation of the resultset you might need not only
JOIN
these two tables but alsoPIVOT
the resultset. You can do that with a query likeSample output:
Here is SQLFiddle demo
Now to be able to filter your records based on meta keys and meta values you'll have to use
HAVING
clauseFor example if you want to get invoices made by customer Jhon Doe
Output:
Here is SQLFiddle demo
For this circumstance you want to use a "JOIN". Check out http://www.w3schools.com/sql/sql_join.asp, which is almost exactly what you want to do.
It'll end something like:
Also note that your table name is wrong for the second table.
To start, I would do
What have you done?
First, you should not attempt to JOIN both tables, because their table structures are dissimilar. Let us create a view that consumes
WP_POSTMETA
's data, consolidating it.Joining
WP_POSTMETA
with itself X-1 times for every X fields you are interested in produces 0 to X lines for everyPost_ID
. Use theWHERE
clause to get 1 column from each copy of the table and reduce the total amount of lines perPost_ID
to 1 (or none).Filter out the rubbish and voilà!
NOTE:
[table_name2]
can be calledtemp0
,[table_name3]
calledtemp1
,[table_name4]
calledtemp2
, or whatever you wish.This will generate an output that can be made into a
view
by prependingand this view
JOIN
ed to WP_POST