I'm trying to:
- Select distinct (to ID) ID (post identification) and post_title from wp_posts where post_status = publish and post_type = product;
- Select distinct (to post_id) post_id and meta_value from wp_postmeta;
I need to do this with one select statement, so I've tried as many as I'd imagine and search for. The last I tried was this one:
SELECT a.ID,a.post_title,b.post_id,b.meta_value FROM ( SELECT DISTINCT ID FROM wp_posts UNION SELECT DISTINCT post_id FROM wp_postmeta ) x LEFT JOIN wp_posts a ON x.ID = a.ID LEFT JOIN wp_postmeta b ON x.post_id = b.post_id
But, when I try, it tells me:
#1054 - Unknown column 'x.post_id' in 'on clause'
I'd not imagine anything, would someone help me here?
---- edit ----
@Rahul,
This is good, but still returning non distinct values, I'm using this, (note, common columns: a.ID = yy.post_id):
SELECT a.ID, a.post_title, b.post_id, b.meta_value FROM wp_posts a LEFT JOIN ( SELECT DISTINCT ID FROM wp_posts )xx ON a.ID = xx.ID LEFT JOIN ( SELECT DISTINCT post_id FROM wp_postmeta )yy ON a.ID = yy.post_id LEFT JOIN wp_postmeta b ON b.post_id = yy.post_id WHERE a.post_type = 'product' AND a.post_status = 'publish' LIMIT 0 , 30
It's return:
ID post_title post_id meta_value
141 Pastel de Teste 141 1
141 Pastel de Teste 141 1436921168:1
141 Pastel de Teste 141 123
141 Pastel de Teste 141 visible
UNION
takes place there is only one table with a single column. This column is named after the name of the column of the first table participating in theUNION
, i.e.ID
. Hence there is nopost_id
, you should usex.ID
instead. – Giorgos Betsos