开发者

How could I tidy this MySQL code and make it more readable?

SELECT
    *
FROM
    `table_1`
WHERE
    `id` = 
            (
                SELECT 
                    `an_id` 
                FROM
                    `table_2` 
                WHERE
                    `id` = 
                            (
                                SELECT 
                                    `a开发者_运维技巧nother_id` 
                                FROM 
                                    `table_3`
                                WHERE 
                                    `id` = 
                                            (
                                                SELECT                      
                                                    `yet_another_id` 
                                                FROM 
                                                    `table_4` 
                                                WHERE 
                                                    `id` = 123
                                            )
                            )
            )

Pretty ugly right?

I'm guessing I could use JOINs here - but how?


select t1.*
from
    table1 t1,
    table2 t2,
    table3 t3,
    table4 t4
where
    t4.id = 123
    and t3.id = t4.yet_another_id
    and t2.id = t3.another_id
    and t1.id = an_id;


Does this return the same results on your data?:

SELECT
  table_1.*
FROM
  table_1
  INNER JOIN table_2
    ON table_1.id = table_2.an_id
  INNER JOIN table_3
    ON table_2.id = table_3.another_id
  INNER JOIN table_4
    ON table_3.id = table_4.tet_another_id
WHERE
  table_4.id = 123

Even if it does, it's still worth benchmarking the two to see which is actually faster.


Try this:

SELECT 
    t1.* 
FROM 
    table_1 AS t1 
JOIN 
    table_2 AS t2 ON (t1.id = t2.id) 
JOIN 
    table_3 AS t3 ON (t2.id = t3.id)
JOIN 
    table_4 AS t4 ON (t3.id = t4.id)
WHERE 
    t4.id = 123

Maybe this helps you..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜