ThinkPHP5ÖÐÅÌÎÊÒªÁìÔõôʹÓÃ
Ò»¡¢ÅÌÎÊÖ®ºÍµÄʹÓÃÒªÁì
ThinkPHP5ÖпÉÒÔͨ¹ýqueryºÍsumÒªÁìʵÏÖÅÌÎÊÖ®ºÍ¡£queryÒªÁì±»ÓÃÓÚ½¨ÉèSQLÓï¾ä£¬¶øsum·½¹æÔòÓÃÓÚÖ´ÐÐSQLÓï¾ä²¢´ÓÅÌÎÊЧ¹ûÖлñÈ¡×ܺ͡£
Ïêϸ¶øÑÔ£¬ÅÌÎÊÖ®ºÍµÄʹÓÃÒªÁìÈçÏ£º
//µ¼ÈëÃüÃû¿Õ¼ä<br/>use think\Db;<br/><br/>//¹¹½¨SQLÓï¾ä<br/>$result = Db::query('SELECT SUM(column_name) AS total FROM table_name');<br/><br/>//È¡³öÅÌÎÊЧ¹ûÖеĺÍ<br/>$sum = $result[0]['total'];<br/>
µÇ¼ºó¸´ÖÆ
ÎÒÃÇÔÚÒÔÉÏ´úÂëÖÐÏÈÒýÓÃÁËthink\DbÃüÃû¿Õ¼ä£¬½Ó×ÅʹÓÃqueryÒªÁì±àдÁËSQLÓï¾ä¡£ÆäÖУ¬SUM(column_name)ÓÃÓÚÅÌËãÁÐcolumn_nameÖÐËùÓÐÖµµÄºÍ£¬AS totalÓÃÓÚ½«ÅÌËãЧ¹ûµÄÃû³ÆÉèΪtotal¡£È»ºó£¬ÎÒÃÇÖ´ÐÐqueryÒªÁ죬À´ÅÌÎÊSQLÓï¾ä²¢»ñÈ¡ÅÌÎÊЧ¹ûÖеĺͣ¬¼´$result0¡£
¶þ¡¢ÅÌÎÊÖ®ºÍµÄʵÀý
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
ÏÂÃæͨ¹ýÒ»¸öʵÀýÀ´ÏÈÈÝThinkPHP5ÖÐÅÌÎÊÖ®ºÍµÄʹÓÃÒªÁì¡£
¼ÙÉèÎÒÃǵÄÊý¾Ý¿âÖÐÓÐÒ»ÕÅÃûΪstudentsµÄ±í£¬ÆäÖаüÀ¨ÁËÿ¸öѧÉúµÄЧ¹ûÐÅÏ¢£¬ÈçÏÂËùʾ£º
id name grade1 grade2 grade3<br/>1 ÕÅÈý 80 90 85<br/>2 ÀîËÄ 75 82 93<br/>3 ÍõÎå 90 85 87<br/>...<br/>
µÇ¼ºó¸´ÖÆ
ÎÒÃÇÐèÒªÅÌÎÊËùÓÐѧÉúµÄ×ÜЧ¹û²¢Æ¾Ö¤×ÜЧ¹ûµÄ½µÐòÅÅÐò¡£ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏ´úÂëÀ´ÊµÏÖ£º
//µ¼ÈëÃüÃû¿Õ¼ä<br/>use think\Db;<br/><br/>//¹¹½¨SQLÓï¾ä<br/>$sql = "SELECT id, name, (grade1 + grade2 + grade3) AS total_grade FROM students ORDER BY total_grade DESC";<br/><br/>//Ö´ÐÐSQLÓï¾ä²¢È¡³öÅÌÎÊЧ¹ûÖеĺÍ<br/>$results = Db::query($sql);<br/><br/>//Êä³öÅÌÎÊЧ¹û<br/>echo "<table>";<br/>echo "<tr><th>ID</th><th>ÐÕÃû</th><th>×ÜЧ¹û</th></tr>";<br/>foreach($results as $result){<br/> echo "<tr><td>".$result['id']."</td><td>".$result['name']."</td><td>".$result['total_grade']."</td></tr>";<br/>}<br/>echo "</table>";<br/>
µÇ¼ºó¸´ÖÆ
ÎÒÃÇÊ×ÏÈÒýÈëÁËthink\DbÃüÃû¿Õ¼ä£¬²¢ÇÒ½ÓÄÉSELECTÓï¾ä¹¹½¨ÁËSQLÓï¾ä¡£ÆäÖУ¬(grade1 + grade2 + grade3)ÓÃÓÚÅÌËãÿ¸öѧÉúµÄ×ÜЧ¹û£¬²¢½«ÅÌËãЧ¹ûµÄÃû³ÆÉèΪtotal_grade¡£È»ºó£¬ÎÒÃÇÖ´ÐÐqueryÒªÁìÀ´Ö´ÐÐSQLÓï¾ä²¢»ñÈ¡ÅÌÎÊЧ¹û¡£×îºó£¬ÎÒÃÇÔÚÒ³ÃæÉÏÊä³öÅÌÎÊЧ¹û¡£
ÒÔÉϾÍÊÇThinkPHP5ÖÐÅÌÎÊÒªÁìÔõôʹÓõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡