我有两张表tasks
和task_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 |
+---------+----------------+-----------+
| ... | ... | ... |
+---------+----------------+-----------+
task_category
+---------+----------------+
| 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查询返回dublicated类别条目...如何连接表以获得结果,如提供的示例?
答案 0 :(得分:2)
SELECT task_name, task_category
FROM task LEFT JOIN task_category
ON task.category_id=task_category.id
然后,您遍历结果以构建表格 你将有重复的catogories,但你不必将它们写入你的表:
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)