Optimizing query, select from many tables

72 Views Asked by At

I have a SQL script which joins four tables. I am using many AND operations. Is there any solution how to optimize this script?

SELECT s.ACCESS_CODE, a.ACCESS_CODE, MIN(b.ID), b.NAME, a.USER_ID, b.PARENT_ID,b.UPDATE_TIME
FROM b_disk_simple_right s, b_user_access a, b_disk_object b, b_file f
WHERE s.ACCESS_CODE = a.ACCESS_CODE 
  AND a.USER_ID = '".$userID."' 
  AND s.OBJECT_ID=b.ID 
  AND f.ID = b.FILE_ID
  AND b.DELETED_BY=0
  AND f.MODULE_ID = 'disk' 
GROUP BY b.ID
2

There are 2 best solutions below

0
On

Try inner join as below :

SELECT        s.ACCESS_CODE, a.ACCESS_CODE AS Expr1, MIN(b.ID) AS Expr2, b.NAME, a.USER_ID, b.PARENT_ID, b.UPDATE_TIME
FROM          b_disk_simple_right AS s INNER JOIN
              b_user_access AS a ON s.ACCESS_CODE = a.ACCESS_CODE CROSS JOIN
              b_disk_object AS b CROSS JOIN
              b_file AS f
WHERE        (a.USER_ID = '".$userID."') AND (s.OBJECT_ID = b.ID) AND (f.ID = b.FILE_ID) AND (b.DELETED_BY = 0) AND (f.MODULE_ID = 'disk')
GROUP BY b.ID
0
On

First, you should find out whether this operation is actually restricting the speed of your application. If it's not, then it's probably not worth worrying about. Finally, without changing the schema or indices you won't squeeze much more out of it (a decent DB system will optimise it for you before running it).