-1

我有两张桌子taskstask_category

任务

+---------+----------------+-----------+
|   ID    |task_category_id| task_name |
+---------+----------------+-----------+
|    1    |        1       |    task1  |
+---------+----------------+-----------+
|    2    |        1       |    task2  |
+---------+----------------+-----------+
|    3    |        1       |    task3  |
+---------+----------------+-----------+
|    4    |        2       |    task4  |
+---------+----------------+-----------+
|    5    |        2       |    task5  |
+---------+----------------+-----------+
|    6    |        3       |    task6  |
+---------+----------------+-----------+
|    ...  |      ...       |    ...    |
+---------+----------------+-----------+

任务类别

+---------+----------------+
|   ID    |task_category   | 
+---------+----------------+
|    1    |  category_1    |
+---------+----------------+
|    2    |  category_2    |
+---------+----------------+
|    3    |  category_3    |
+---------+----------------+
|    4    |  category_4    |
+---------+----------------+

我需要像这样输出html表:

 <table>
  <tr>
   <td>
   category_1
   </td>
  </tr>
  <tr>
   <td>
   task_1
   </td>
  </tr>
  <tr>
   <td>
   task_2
   </td>
  </tr>
  <tr>
   <td>
   task_3
   </td>
  </tr>
  <tr>
   <td>
   category_2
   </td>
  </tr>
  <tr>
   <td>
   task_4
   </td>
  </tr>      
 </table>

SELECT DISTINCT factor.* , cat.task_name as factors
            FROM task_category as factor
            LEFT JOIN task AS cat ON factor.id = cat.task_category_id

此 mysql 查询返回重复的类别条目...如何连接表以获得如提供的示例中的结果?

4

1 回答 1

2
SELECT task_name, task_category 
FROM task LEFT JOIN task_category 
ON task.category_id=task_category.id

然后你遍历结果来构建你的表。
您将有重复的类别,但您不必将它们写入表中:

echo '<table>';
$last_category='DUMMY_NO_CATEGORY';
foreach ($rows as $row) { // <-- Please adapt to your database connection
  if ($row['task_category']!=$last_category) {
    echo '<tr><td>'.$row['task_category'].'</td></tr>';
    $last_category=$row['task_category'];
  }
  echo '<tr><td>'.$row['task_name'].'</td></tr>';
}
echo '</table>';

(假设 PHP)

于 2013-01-14T09:47:05.383 回答