繁体   English   中英

联接查询:如何将联接table2中的结果作为table1中的数组返回

[英]Join query: How to return results from join table2 as an array in the table1

我需要显示一篇文章列表,其中包含每篇文章对应的全套标签。 我试图做这个查询:

SELECT articles.article_id, `title`, `text`, tags.tag_name 
FROM `articles` 
LEFT JOIN `tags` 
on articles.article_id = tags.article_id 
WHERE articles.author_id = 150342

但是,对于每个标签,该查询从表articles返回同一行的次数与标签的返回次数相同。

像这样:

Array
(
  [0] => Array
  (
    [article_id] => 1
    [title] => title1
    [text] => text1
    [tag_name] => tag1
  )
 [1] => Array
 (
    [article_id] => 1
    [title] => title1
    [text] => text1
    [tag_name] => tag2
 )
 [2] => Array
 (
    [article_id] => 1
    [title] => title1
    [text] => text1
    [tag_name] => tag3
 )
)

有没有一种方法可以为每个文章在数组中返回tag_name? 看起来像这样:

Array
(
 [0] => Array
 (
    [article_id] => 1
    [title] => title1
    [text] => text1
    [tag_name] => array ([0] => tag1, [1] => tag2, [2] => tag3)
 )
)

不是数组,但是您可以使用逗号分隔的字符串,

SELECT articles.article_id, `title`, `text`, GROUP_CONCAT(tags.tag_name )as tg_name
FROM `articles` 
LEFT JOIN `tags` 
on articles.article_id = tags.article_id 
WHERE articles.author_id = 150342
GROUP BY tags.article_id

不,您应该在php中执行两个查询或以不同的方式处理/解析数据。

喜欢:

$articles = array();

foreach($query_result as $row) {

  if (!array_key_exists($row['article_id'], $articles))
     $articles[$row['article_id']] = array(
       "title" => $row["title"],
       "text" => $row["text"],
       // etc
       "tags" => array()
     );

  $articles[$row['article_id']]['tags'][] = $row["tag_name"];

}

首先从查询中获取结果,然后将'tag_name'从字符串分解为Array:

 SELECT A.article_id, A.`title`, A.`text`, group_concat(T.tag_name) a 'tag_name'
    FROM `articles`  A
    LEFT JOIN `tags` T
    on A.article_id = T.article_id 
    WHERE A.author_id = 150342 
    group by A.article_id, A.`title`, A.`text`

范例:

<?php
// Example 1
$tag_name = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>

mySQL中没有数组的概念,但是您可以将它们作为每个artid的tag_names的逗号分隔列表

SELECT articles.article_id, `title`, `text`, GROUP_CONCAT(tags.tag_name) as tag_names
FROM `articles` LEFT JOIN `tags` 
on articles.article_id = tags.article_id 
WHERE articles.author_id = 150342 
GROUP BY articles.article_id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM