PHP vs MySQL Performance ( if , functions ) in que

2019-04-24 02:17发布

I just see this artice

i need to know what's is best berformance in this cases

if statment in query

SELECT *,if( status = 1 , "active" ,"unactive") as status_val FROM comments

VS

<?php
    $x = mysql_query("SELECT * FROM comments");

     while( $res = mysql_fetch_assoc( $x ) ){
       if( $x['status'] == 1 ){
             $status_val = 'active';
        }else{
             $status_val = 'unactive';
        }
     }
  ?>

Cut 10 from string

SELECT * , SUBSTR(comment, 0, 10) as min_comment FROM comments

VS

<?php
    $x = mysql_query("SELECT * FROM comments");

     while( $res = mysql_fetch_assoc( $x ) ){
       $min_comment = substr( $x['comment'],0,10 ) ;
     }
  ?>

etc ????? and When i use MYSQL functions or PHP functions ?

5条回答
劫难
2楼-- · 2019-04-24 02:45

Here is a nice description of your question: Doing calculations in MySQL vs PHP

In case of the second example the speed issue can be significant. First of all you do not know how big are your comments, so in case of

$x = mysql_query("SELECT * FROM comments");

 while( $res = mysql_fetch_assoc( $x ) ){
   $min_comment = substr( $x['comment'],0,10 ) ;
 }

you ask your server to return you everything (here I mean the whole length of the comment) and this can be significant. Multiplying by the number of rows in the table it can be quite big size of data, which you have to transfer between php and sql. In the second case this SELECT * , SUBSTR(comment, 0, 10) as min_comment FROM comments this will be already done on the server and will not require additional memory.

In case of the first example, I think it is also better to do it on sql side, because you will still need to do additional loop afterwards. Apart from this, people who will be reading your code might be confused why exactly do you need that code.

查看更多
做个烂人
3楼-- · 2019-04-24 02:47

In that case, using MySQL functions keeps you from looping in PHP and saves you a lot of code.

In other cases they have no alternative : for instance, when you use them in the WHERE part.

In terms of performance, the difference is trivial in most cases : use the simplest solution.

查看更多
【Aperson】
4楼-- · 2019-04-24 02:51

I'd say it all depends on the systems on either end and current load. Typically DB servers are more stout than desktop machines and it would be faster to do the whole thing on the DB side rather than split it and use PHP partly.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-04-24 02:56

It depends. From a network point of view, in the first VS, PHP wins and in the second VS, MYSQL wins. That's because you send less data via socket. And thus the script becomes faster.

查看更多
劫难
6楼-- · 2019-04-24 03:04

Only answer: Measure it! You have two working solutions and want to achieve the best execution time.

查看更多
登录 后发表回答