我有一个成功的查询,当前返回除一个表之外的所有数据。最后一个表包含元数据,它是一对多关系(一个产品,多个记录和相关数据)。
有没有办法将带有值的字段附加到现有查询的末尾,这样我仍然可以使用mysql_fetch_array()命令访问PHP中的记录集?
基本上我想查询带有产品ID的任何记录,然后附加多个附加字段。
在考虑之后我真的想知道我是否可以在记录集中包含一个数组(即元数据的结果数组)并通过PHP访问它?
工作查询:
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
结果:
ID: 43875
category: 1
state: CO
city: Denver
zip: 80221
sponsor: 1
title: The coolest thing ever
duration: 2 years
price: 10
frequency:: Month
获取正确元数据的第二个查询 -
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
结果:
meta_value:
'5-10 tickets'
'General Admission'
我想将这两个字段添加到记录顶部..但不知道如何将查询结果中的所有字段附加到单个已存在的记录中。
- 解决 -
已调整查询以考虑GROUP_CONCAT,如下所示
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
数据结果看起来不错,包括名为“titles”和“metas”的2个字段,看起来像这样
titles: 'Number of Tickets,Purchased Seats'
metas: '5-10,General Administration'
现在THOSE ..我可以在PHP中使用..因为它们具有相同数量的元素,我只需将它们解析成数组,我可以更好地使用:)
答案 0 :(得分:2)
除了上面的评论之外,听起来GROUP_CONCAT()
会为您提供您所追求的内容。它不会将meta_values
作为数组返回,而是作为字符串返回(例如,每个值由<br/>
分隔,以便它们可以直接以HTML格式发送):
SELECT
offers.*,
c.short_name AS sponsorName,
c.logo AS sponsorLogo,
GROUP_CONCAT(mo.name ORDER BY meta_option ASC SEPARATOR '<br/>') AS meta_values
FROM
offers
LEFT JOIN sponsors AS c ON c.id = offers.sponsor
LEFT JOIN offer_metas AS o ON o.offer_id = offers.id
LEFT JOIN meta_options AS mo ON mo.id = offer_metas.meta_option
ORDER BY end_date ASC;
请注意,如果您需要转义它们可能包含的任何HTML的元值,您需要选择不同的分隔符(可能是U+001E,INFORMATION SEPARATOR TWO
?)并让PHP替换它转义任何包含的HTML后,带有合适HTML的分隔符。