简体   繁体   中英

MYSQL slow query when getting total rows from another table using while loop

I am new to mysql and I am attempting to get all ID from another table where ID is equal to ID from table 1 and another conditions.

Table 1

+---------------+
| ID model line |
+---------------+
| 1   XX    C1  |
| 2   AA    C3  |
| 3   SS    C1  |
+---------------+

Table 2 ( So if my query is ID = 1 AND model = XX GROUP BY line the total rows from table 2 will return 3 since ID 1,4 and 5 is true.

+----------------------------+
| ID InspectionID model line |
+----------------------------+
| 1   1            XX    C1  |
| 2   1            AA    C3  |
| 3   1            SS    C1  |
| 4   1            XX    C2  |
| 5   1            XX    C4  |
+----------------------------+

So far i have this query inside a PHP while loop it return what i wanted but the query is really slow.

$query = "SELECT * FROM table2 WHERE inspectionID = '$ID' AND model = '$modelID' GROUP BY line

So i think the best way is to join table1 and table2 and add a column total sadly my knowledge on mysql and joining table is limited, any suggestions is appreciated.

my target is to create below.

+---------------------+
| ID model line total |
+---------------------+
| 1   XX    C1    3   |
| 2   AA    C3    0   |
| 3   SS    C1    0   |
+---------------------+

Pretty simple join and aggregation. working demo (note demo includes both answers so far and results.)

We left join so we keep all records from table 1 and join to table 2 to get records matching from table 1. We set the limit on model on the join itself so the filtering is applied to the table2 before the join occurs. thus the count will only include model XX and all other counts for models will be zero.

SELECT T1.ID, T1.Model, T1.Line, count(T2.ID)
FROM table1 T1
LEFT JOIN Table2 T2
 on T1.Model = T2.Model
and T2.Model = 'XX'  
GROUP BY T1.ID, T1.Model, T1.Line
ORDER BY T1.ID

Just create an SQL View :

CREATE VIEW TABLE_1_2_VIEW AS
SELECT A.id, A.model, A.line, B.inspectionID, COUNT(B.ID) Total
FROM table_1 A LEFT JOIN table_2 B
ON A.model=B.model
GROUP BY A.id, A.model, A.line, B.inspectionID
ORDER BY A.id, A.model, A.line;

You can query the data from this view as if it were a table.

SELECT id, model, line, IF(model='XX', Total, 0) Total 
FROM TABLE_1_2_VIEW
WHERE inspectionID=1;

Just that the data in this view would not be updatable.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM