我有两个表(条目和标签)和一个多对多链接表。现在,我正在查询以检索符合我条件的所有条目,并查询每个条目以检索标签。
有没有办法说,在第一个查询中通过新列将标签作为数组返回?
最佳答案
这个查询:
SELECT e.id entry_id
, GROUP_CONCAT(t.txt ORDER BY t.txt) tags
FROM entry e
LEFT JOIN entry_tag et
ON e.id = et.entry_id
LEFT JOIN tag t
ON et.tag_id = t.id
GROUP BY e.id
将以逗号分隔的列表形式返回标签。您可以阅读 GROUP_CONCAT 以获得更多选项:http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_group-concat
在您的应用中,您应该能够很容易地将其扩展为数组。例如在 php 中,你可以使用 explode
: http://php.net/manual/en/function.explode.php
如果您需要来自 tag
或 entry_tag
表的更多属性,您可以添加更多的 GROUP_CONCAT
列,或者考虑一些序列化为您的数据设置格式(如 JSON)并在其上使用 GROUP_CONCAT
,或者您可以简单地为每个条目返回多行并在应用程序中处理结果以将标签与条目保持在一起:
$sql = '
SELECT e.id entry_id
, t.id tag_id
, t.txt tag_text
, t.published tag_published
FROM entry e
LEFT JOIN entry_tag et
ON e.id = et.entry_id
LEFT JOIN tag t
ON et.tag_id = t.id
ORDER BY e.id
';
$result = mysql_query($ql);
$entry_id = NULL;
$entry_rows = NULL;
while ($row = mysql_fetch_assoc($result)) {
if ($entry_id != $row['entry_id']) {
if (isset($entry_id)) { //ok, found new entry
process_entry($entry_rows); //process the rows collected so far
}
$entry_id = $row['entry_id'];
$entry_rows = array();
}
$entry_rows[] = $row; //store row for his entry for later processing
}
if (isset($entry_id)){ //process the batch of rows for the last entry
process_entry($entry_rows);
}
关于php - 多层MySQL查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2307384/