I have a successful query that currently returns all data except for one table. The last table contains meta data where it is a one to many relationship (one product, multiple records with related data).
Is there a way to append a field with a value to the end of an existing query so that I can still access the record set in PHP with a mysql_fetch_array() command?
essentially I want to query for any records with the product ID, and then append multiple additional fields.
After thinking about it i was actually wondering if I can include an array within the records set (i.e. the array of results for the meta data) and access that through PHP?
Working Query:
SELECT offers.*, c.short_name AS sponsorName, c.logo AS sponsorLogo
FROM offers LEFT JOIN sponsors AS c ON c.id=offers.sponsor ORDER BY end_date ASC
Results:
ID: 43875
category: 1
state: CO
city: Denver
zip: 80221
sponsor: 1
title: The coolest thing ever
duration: 2 years
price: 10
frequency:: Month
Second query that gets the right meta data-
SELECT mo.`name` AS meta_value FROM offer_metas
LEFT JOIN meta_options AS mo ON mo.id = offer_metas.meta_option
WHERE offer_id='48735' ORDER BY meta_option ASC
results:
meta_value:
'5-10 tickets'
'General Admission'
I want to add those two fields to the record up top .. but don’t know how to append all fields within a query result into a single already existing record.
–SOLVED–
Query has been adjusted to account for GROUP_CONCAT as follows
SELECT
offers.*,
s.short_name AS sponsorName,
s.logo AS sponsorLogo,
GROUP_CONCAT( mn.title) titles,
GROUP_CONCAT( mo.`name`) metas
FROM offers
LEFT JOIN sponsors AS s ON s.id = offers.sponsir
INNER JOIN offer_metas ON offer_metas.offer_id = offers.id
INNER JOIN meta_options as mo ON offer_metas.meta_option = mo.id
INNER JOIN meta_names as mn ON mo.category = mn.category AND mo.cat_seq = mn.seq
ORDER BY end_date ASC
data results looked good including 2 fields called “titles” and “metas” that looked like this
titles: 'Number of Tickets,Purchased Seats'
metas: '5-10,General Administration'
now THOSE .. I can work with in PHP .. and since they have the same number of elements i’ll just parse them into an array i can better work with 🙂
Further to your comments above, it sounds like
GROUP_CONCAT()will give you what you’re after. It won’t return themeta_valuesas an array, but rather as a string (e.g. with each value separated by<br/>in order that they can be emitted directly as HTML):Note that, if you need to escape the meta values for any HTML they might contain, you’ll need to choose a different separator (perhaps U+001E,
INFORMATION SEPARATOR TWO?) and have PHP replace that separator with suitable HTML after escaping any contained HTML.