我正在尝试输出一个“项目”列表,这些项目都包含“标签”列表。由于标签用于多个项目,我使用的是名为“tag_rel”的桥接表。
$query = mysql_query("SELECT i.*, t.name
FROM items AS i
LEFT JOIN tag_rel AS tr ON (tr.item = j.id)
LEFT JOIN tags AS t ON (t.id = tr.tag)
ORDER by i.id DESC");
while($row = mysql_fetch_array($query)){
我认为这会给我一份我的物品清单。但是如何输出每个项目的给定标签列表?
我知道我不应该对每个查询进行第二次查询,即:
$query = mysql_query("SELECT i.*
FROM items AS i
ORDER by i.id DESC L");
while($row = mysql_fetch_array($query)){
$query2 = mysql_query("SELECT t.name
FROM tag_rel AS tr
LEFT JOIN tags AS t ON (t.id = tr.tag)
WHERE tr.item=$row[id]");
while($row2 = mysql_fetch_array($query)){
任何提示?
非常感谢!
答案 0 :(得分:1)
试试这个:
SELECT i.*, GROUP_CONCAT(t.name) tagList
FROM items AS i
LEFT JOIN tag_rel AS tr ON (tr.item = j.id)
LEFT JOIN tags AS t ON (t.id = tr.tag)
GROUP BY i.id
ORDER BY i.id DESC