0

我有这个 sql 语句加入 3 个表:

SELECT * FROM `int_news` 
                       LEFT JOIN tl_member ON int_news.member_id = tl_member.id
                       LEFT JOIN tl_news ON int_news.news_id = tl_news.id

3个表是这样的:

表1(int_news)ID、member_id、news_id

表 2 (tl_member) id, firstname, lastname

表 3 (tl_news) id, 标题

到目前为止一切顺利,但似乎我脑子里有一个大黑洞,让我无法解决如何输出这样的结果

对于每个“标题”,我想要所有姓氏,例如

headline 1       Jonny
                 Walker
                 Jim

headline 2       Knopf
                 Jon
                 Doe
4

3 回答 3

1

听起来您看起来像一个枢轴,因此如果您按标题对查询进行分组,它将每个姓氏显示为一列。

我发现这个关于 mysql 枢轴的好教程可能对你有所帮助http://www.artfulsoftware.com/infotree/queries.php#78

headline 1       Jonny    Walker    Jim

headline 2       Knopf    Jon       Doe

这是一个可以做到这一点的循环 *原谅我的 php 已经有一段时间了。

$curHeadline = "";

while ( $db_field = mysql_fetch_assoc($result) ) {

    if($curHeadline != $db_field['headline'])
    {
        $curHeadline = $db_field['headline'];
        print $curHeadline . $db_field['ID']
    }

    print $db_field['lastName'] . "<BR>";
}
于 2013-01-13T23:04:45.970 回答
-1

这样的事情会模糊地反映你的情况吗?

<?php

$sql = "
    SELECT
        `int_news`.`ID` AS `int_news_ID`, 
        `int_news`.`member_id`, 
        `int_news`.`news_id`, 
        `t1_member`.`id` AS `t1_member_id`, 
        `t1_member`.`firstname`,
        `t1_member`.`lastname`,      /* desired */
        `t1_news`.`id` AS `t1_news_id`, 
        `t1_news`.`headline`         /* desired */
    FROM
        `int_news` 
    LEFT JOIN `tl_member` ON `int_news`.`member_id` = `tl_member`.`id`
    LEFT JOIN `tl_news` ON `int_news`.`news_id` = `tl_news`.`id`
";

$res = mysql_query($query);

$arrHeadings = array();
while($row = mysql_fetch_assoc($res)) {
 // We want to output the results in groups of headings
 $arrHeadings[$row['heading']][] = $row;
}

// Don't forget to cleanse for html output (unlike below)
// Loop through the headers
foreach($arrHeadings as $heading=>$arrRow) {
 echo '<dl>';
 echo '<dt>'.$heading.'</dt>';
 echo '<dd>';

 // Loop through rows with the same header
 foreach($arrRow as $index=>$dbRow) {
  echo $dbRow['lastname'].'<br />';
 }

 echo '</dd>';
 echo '</dl>';
}

?>
于 2013-01-13T23:22:52.840 回答
-1

试试这个 mysql :

SELECT tlnews.headline, GROUP_CONCAT(tl_member.last_name)
FROM `int_news`  LEFT JOIN tl_member ON int_news.member_id = tl_member.id
                 LEFT JOIN tl_news   ON int_news.news_id   = tl_news.id
GROUP BY 1;

Expected Output:

headline1  Johnny,Walker,Jim
headline2  Knopf,Jon,Doe
...
于 2013-01-13T23:44:24.123 回答