2012-01-24 4 views
0

に基づいて複数のレコードを取得する方法この問題を解決する方法を教えてください。カテゴリ

は、私は2つのテーブル

カテゴリがあります。

IDを....カテゴリ....一般的な親


1 .... .... 0

2 ....ニュース.... 0

ニュース: id ....の見出しの見出しカテゴリ_id


1 .... headline1 .... 1

2 .... headline2 .... 2

3 .... headline3 .... 2

4 .... headline4 .... 1

と私はこのMYSQL

コードを有する:

SELECT * FROM news INNER JOIN categories ON news.category_id=categories.id group by category_id,date 

今私は、私はこのような結果を得るカテゴリ

に基づいて行を取得したい:

一般的なカテゴリ:

headline1

headline4

ニュースカテゴリ:

headline2

headline3

私のmysqlのログを参照してください、この男

+0

[複数のHTMLテーブルの結果の表示](http://stackoverflow.com/questions/8981332/display-results-in-multiple-html-tables/8981447#8981447)を表示 – bowlerae

答えて

2
$getcategories = mysql_query("SELECT DISTINCT id FROM categories"); 
$categories = mysql_num_rows($getcategories); 

if($categories > 0){ 
    echo "<table width='100%' cellspacing='0' cellpadding='0'>"; 

    while ($rowcategories = mysql_fetch_assoc($getcategories)) { 

    $category_id = $rowcategories['id']; 
    $category_title = $rowcategories['category']; 

    $getnews = mysql_query("SELECT * FROM news WHERE category_id = '$category_id'"); 
    $news = mysql_num_rows($getnews); 


     if($news > 0){ 
     echo "<tr><td>$category_title</td></tr>"; 

      while ($rownews = mysql_fetch_assoc($getnews)) { 

      $news_headline = $rownews['headline']; 
      // all other info you want to pull here 

      echo "<tr><td>ROW WITH NEWS INFO HERE</td></tr>"; 

      } // end news loop 
     } // end if news > 0 
    echo "</table>"; 
    } // end if categories > 0 
} // end categories loop 
+0

私はあなたたちを愛してください:) –

1
You dont need group by. You need **order by**. 

で私を助けてください。

mysql> create table categories (id int , category varchar(20), parent int); 
Query OK, 0 rows affected (0.06 sec) 

mysql> create table headlines (id int, headline varchar(30), category_id int); 
Query OK, 0 rows affected (0.05 sec) 

mysql> insert into categories values (1, 'general', 0) , (2, 'news', 0); 
Query OK, 2 rows affected (0.00 sec) 
Records: 2 Duplicates: 0 Warnings: 0 

mysql> insert into headlines values (1, 'headline1', 1), (2, 'headline2', 2), (3, 'headline3', 2), (4, 'headline4', 1); 
Query OK, 4 rows affected (0.00 sec) 
Records: 4 Duplicates: 0 Warnings: 0 


mysql> select category , headline from headlines as h join categories as c on (c.id = h.category_id) order by category, headline ; 
+----------+-----------+ 
| category | headline | 
+----------+-----------+ 
| general | headline1 | 
| general | headline4 | 
| news  | headline2 | 
| news  | headline3 | 
+----------+-----------+ 
4 rows in set (0.00 sec)