Home  >  Article  >  PHP Framework  >  How to use query method in ThinkPHP5

How to use query method in ThinkPHP5

WBOY
WBOYforward
2023-05-28 12:46:401498browse

1. How to use the sum of queries

In ThinkPHP5, the sum of queries can be realized through the query and sum methods. The query method is used to create a SQL statement, while the sum method is used to execute the SQL statement and obtain the sum from the query results.

Specifically, the query sum is used as follows:

<code>//导入命名空间<br/>use think\Db;<br/><br/>//构建SQL语句<br/>$result = Db::query(&#39;SELECT SUM(column_name) AS total FROM table_name&#39;);<br/><br/>//取出查询结果中的和<br/>$sum = $result[0][&#39;total&#39;];<br/></code>

In the above code, we first quoted the think\Db namespace, and then used the query method to write the SQL statement. Among them, SUM(column_name) is used to calculate the sum of all values ​​in column column_name, and AS total is used to set the name of the calculation result to total. Then, we execute the query method to query the SQL statement and obtain the sum of the query results, which is $result0.

2. Examples of sum of queries

The following uses an example to introduce the use of sum of queries in ThinkPHP5.

Suppose there is a table named students in our database, which contains the performance information of each student, as shown below:

<code>id  name  grade1  grade2  grade3<br/>1   张三   80      90      85<br/>2   李四   75      82      93<br/>3   王五   90      85      87<br/>...<br/></code>

We need to query the total scores of all students and follow Sort by total score in descending order. We can use the following code to achieve this:

<code>//导入命名空间<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[&#39;id&#39;]."</td><td>".$result[&#39;name&#39;]."</td><td>".$result[&#39;total_grade&#39;]."</td></tr>";<br/>}<br/>echo "</table>";<br/></code>

We first introduced the think\Db namespace and used the SELECT statement to construct the SQL statement. Among them, (grade1 grade2 grade3) is used to calculate the total grade of each student, and the name of the calculation result is set to total_grade. Then, we execute the query method to execute the SQL statement and obtain the query results. Finally, we output the query results on the page.

The above is the detailed content of How to use query method in ThinkPHP5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete