Answer the question
In order to leave comments, you need to log in
How to form a sql query correctly?
Good afternoon.
There are entities: Tasks, rewards for tasks
. There is also a sign for linking tasks with prizes. Multiple prizes can be attached to one task.
Essence of the question: How, when accessing a certain php file via ajax, give data of the format task - its prizes, task - its prizes
Can this be done with one request? I tried using join, but it turns out a lot of duplicate tasks, since there are many prizes for one task. How is it done correctly? Maybe I messed something up with the structure. I would be grateful for any hints.
Answer the question
In order to leave comments, you need to log in
You have a many-to-many relationship. This is the normal circuit for the given example. Here you can read more about it: https://habr.com/ru/post/193380/
Data can be obtained, for example, as follows (tasks_prizes is a join table):
SELECT t.id, t.name_task, p.name_prize
FROM tasks t
LEFT JOIN tasks_prizes tp ON t.id = tp.id_task
LEFT JOIN prizes p ON p.id = tp.id_prize
ORDER BY t.id ASC;
+----+-----------+------------+
| id | name_task | name_prize |
+----+-----------+------------+
| 1 | task #1 | prize #1 |
| 1 | task #1 | prize #2 |
| 2 | task #2 | prize #3 |
| 2 | task #2 | prize #4 |
| 3 | task #3 | prize #5 |
+----+-----------+------------+
$tasks = [
'1' => [
'name_task' => 'task #1',
'prizes' => [
'1' => [
'name_prize' => 'prize #1',
],
'2' => [
'name_prize' => 'prize #2',
]
]
]
];
It is possible through JOIN, simply ignoring the extra information. It is possible with two requests, first the necessary tasks, then their prizes. It is possible to write a complex query with CONCAT and GROUP_CONCAT, generating JSON directly in the query.
Tried through join, but it turns out a lot of duplicate tasks, since there are many prizes for one task.
select task_id, ......, prize_id, .......
from (сложный join)
$out = [];
foreach($rows as $row)
{
$task = &$out[row['task_id']];
$task['id'] = row['task_id'];
$task['name'] = row['name_task'];
.... // другие свойства задачи
if(!array_key_exists('prizes', $task))
{
$task['prizes'] = [];
}
if(!is_null($row['prize_id']))
{
$prize = &$task['prizes'][$row['prize_id']];
$prize['id'] = $row['prize_id'];
..... // другие свойства приза
unset($prize);
}
unset($task);
}
var_dump($out);
I would issue the following when accessing this ajax file:
$result = [
'tasks' => [
1 => ['title' => 'Собрать монеты', 'desc' => 'Подробное описание'],
2 => ...
],
'awards' => [1 => 'Серебро', 2 => 'Золото', 3 => 'Чугун'...],
'prizes' => [[1, 1], [2, 2], [2, 1]...]
];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question