I have two tables tasks
and task_category
:
task
+---------+----------------+-----------+
| 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 |
+---------+----------------+
I need to output html table like this:
<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
this mysql query returns dublicated category entries... how to join tables to get result like in provided example?
SELECT task_name, task_category
FROM task LEFT JOIN task_category
ON task.category_id=task_category.id
Then you iterate through results to build your table.
You'll have duplicate catogories, but you don't have to write them into you table:
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>';
(assuming PHP)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.