Answer the question
In order to leave comments, you need to log in
Which query option is more productive?
There are two tables clients_case and clients of the following structure
Clients
clients_case
+----+-------------------------------------+------------+
| id | cctitle | ccclients |
+----+-------------------------------------+------------+
| 1 | Подготовка бизнес-плана | 2, 3, 7 |
| 2 | Перевод документов | 4,5 |
+----+-------------------------------------+------------+
clients
+----+-------------------------------+
| id | clname |
+----+-------------------------------+
| 1 | Клиент 1 |
| 2 | Клиент 2 |
| 3 | Клиент 3 |
| 4 | Клиент 4 |
| 5 | Клиент 5 |
| 6 | Клиент 6 |
| 7 | Клиент 7 |
+----+-------------------------------+
$sql = "SELECT cc.id, cc.cctitle, cc.ccclients, GROUP_CONCAT(CONCAT(cl.id,',', CAST(cl.clname AS CHAR)) ORDER BY cl.clname SEPARATOR ';') AS cln
FROM clients_case AS cc
LEFT JOIN clients AS cl ON FIND_IN_SET (cl.id, cc.ccclients) > 0
GROUP BY cc.id";
$data = $this->db->select_limit($sql, 0, $size);
case_to_case
+----+--------------+-----------+
| id | client_id | case_id |
+----+--------------+-----------+
| 2 | 2 | 1 |
| 3 | 3 | 1 |
| 4 | 4 | 2 |
| 5 | 5 | 2 |
| 7 | 7 | 1 |
+----+--------------+-----------+
$sql = "SELECT * FROM clients_case";
$data = $this->db->select_limit($sql, 0, $size);
$sql = "SELECT DISTINCT cc.*, cc.id AS id, cl.*
FROM case_to_case AS cc
LEFT JOIN clients AS cl ON cl.id = cc.client_id
GROUP BY cl.id";
$data2 = $this->db->query($sql);
foreach($data as $k => $v)
{
foreach($data2 as $k2 => $rec)
{
if($rec['case_id'] == $v['id'])
{
$data[$k]['clients'][] = $data2[$k2];
}
}
}
Answer the question
In order to leave comments, you need to log in
It's just that the first option is not correct, from the point of view of relational databases. In the "ccclients" column, you are supposed to store the user IDs that belong to this case. This is essentially a Many-to-Many implementation, but this option is not correct. The second option is correct, when Users, Cases, and relationships between users and cases are stored in different tables. Then there will be no problems with selecting Cases and Users.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question