Tuesday, 6 August 2013

MySQL - INNER JOIN and GROUP BY

MySQL - INNER JOIN and GROUP BY

Trying to join two tables and create a report:
wp_posts;
+----+-----------+
| id | post_name |
+----+-----------+
| 1 | Retailer1 |
| 2 | Retailer2 |
+----+-----------+
wp_postmeta;
+---------+-----------------+----------------+
| post_id | meta_key | meta_value |
+---------+-----------------+----------------+
| 1 | street_address | 123 Main St. |
| 1 | city | San Fran |
| 1 | province_state | CA |
| 2 | street_address | 321 Broadway |
| 2 | city | New York |
| 2 | province_state | NY |
+---------+-----------------+----------------+
I'm using the following SQL statement:
SELECT
p.id
, p.post_name
,(IF (pa.meta_key = 'street_address', pa.meta_value, NULL)) as `Address`
,(IF (pa.meta_key = 'city', pa.meta_value, NULL)) as `City`
,(IF (pa.meta_key = 'province_state', pa.meta_value, NULL)) as
`Prov/State`
FROM wp_postmeta pa
left JOIN wp_posts AS p ON pa.post_id = p.id
where (p.post_status = 'publish' and
pa.meta_key = 'street_address')
or (p.post_status = 'publish' and
pa.meta_key = 'city')
Right now I'm getting the following results:
+-----+-------------+---------------+-------------+--------------+
| id | post_name | Address | City | Prov/State |
+-----+-------------+---------------+-------------+--------------+
| 1 | Retailer1 | 123 Main St. | NULL | NULL |
| 1 | Retailer2 | 321 Broadway | NULL | NULL |
| 1 | Retailer1 | NULL | SanFran | NULL |
| 2 | Retailer2 | NULL | New York | NULL |
| 2 | Retailer1 | NULL | NULL | CA |
| 2 | Retailer2 | NULL | NULL | NY |
+-----+-------------+---------------+----------------------------+
Is there any way I can get all these values into one resulset? I suck at
SQL but I seem to be close but still no cigar.
Any ideas? Please help!!!

No comments:

Post a Comment