Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Sải hàng động trong khi tìm nạp các bản ghi từ cơ sở dữ liệu

xin lỗi vì tiếng anh kém của tôi:Ở đây tôi đã trả lời câu hỏi này Cách hiển thị dữ liệu từ cơ sở dữ liệu với rowspan động . Một lần nữa hãy để tôi cố gắng trả lời câu hỏi này. Trước tiên, đừng để chúng tôi làm việc trên truy vấn mysql.

MySql Work:

Trong truy vấn mysql, bạn chưa truy vấn thứ tự theo. Bởi trong cuộc sống thực, bạn không thể ngờ rằng sau tất cả các kỷ lục của tom, kỷ lục hóa đơn sẽ ở đó. Ví dụ, hãy lấy phần chèn sau.

INSERT INTO test_work(ename, sal) 
               VALUES("tom",  100), 
                     ("bill", 450), 
                     ("bill", 100), 
                     ("tom",  200),
                     ("bill", 250),
                     ("bill", 400),
                     ("James", 50);
SELECT * FROM test_work;

Kết quả:

+-------+------+
| ename | sal  |
+-------+------+
| tom   |  100 |
| bill  |  450 |
| bill  |  100 |
| tom   |  200 |
| bill  |  250 |
| bill  |  400 |
| James |   50 |
+-------+------+

Vì vậy, truy vấn mysql của bạn nên được sắp xếp theo ename. Đây cũng là sal của mỗi người nên được phong chức. Vì vậy, truy vấn của chúng tôi:

SELECT * FROM emp ORDER BY ename, sal;

GIẢI MÃ:

  1. Toàn bộ nhiệm vụ chúng ta có thể chia thành 3 phần.
    1. Tìm nạp và lưu trữ dữ liệu Mysql trong mảng.
    2. Tính toán sải hàng
    3. In

Tìm nạp dữ liệu MySql:

Trong quá trình tìm nạp dữ liệu từ máy chủ mysql, chúng ta nên cố gắng sử dụng hàm mysql_fetch_assoc thay vì mysql_fetch_array. Bởi vì mysql_fetch_assoc sẽ chỉ trả về ename và sal. Nhưng mysql_fetch_array sẽ trả về mảng với các chỉ mục ename, sal, 0, 1.

    # connect to mysql server
    # and select the database, on which
    # we will work.
    $conn = mysql_connect('', 'root', '');
    $db   = mysql_select_db('test');

    # Query the data from database.
    $query  = 'SELECT * FROM test_work ORDER BY ename, sal';
    $result = mysql_query($query);

    # Intialize the array, which will 
    # store the fetched data.
    $sal = array();
    $emp = array();

    # Loop over all the fetched data, and save the
    # data in array.
    while($row = mysql_fetch_assoc($result)) {
        array_push($emp, $row['ename']);
        array_push($sal, $row['sal']);
    }

Tính toán khoảng cách hàng:

    # Intialize the array, which will store the 
    # rowspan for the user.
    $arr = array();

    # loop over all the sal array
    for ($i = 0; $i < sizeof($sal); $i++) {
        $empName = $emp[$i];

        # If there is no array for the employee
        # then create a elemnt.
        if (!isset($arr[$empName])) {
            $arr[$empName] = array();
            $arr[$empName]['rowspan'] = 0;
        }

        $arr[$empName]['printed'] = "no";

        # Increment the row span value.
        $arr[$empName]['rowspan'] += 1;
    }

khi bạn sẽ print_r mảng arr, kết quả đầu ra sẽ là:

Array
(
    [bill] => Array
        (
            [rowspan] => 4
            [printed] => no
        )

    [James] => Array
        (
            [rowspan] => 1
            [printed] => no
        )

    [tom] => Array
        (
            [rowspan] => 2
            [printed] => no
        )

)

In với sải hàng:

    echo "<table cellspacing='0' cellpadding='0'>
            <tr>
                <th>Ename</th>
                <th>Sal</th>
            </tr>";


    for($i=0; $i < sizeof($sal); $i++) {
        $empName = $emp[$i];
        echo "<tr>";

        # If this row is not printed then print.
        # and make the printed value to "yes", so that
        # next time it will not printed.
        if ($arr[$empName]['printed'] == 'no') {
            echo "<td rowspan='".$arr[$empName]['rowspan']."'>".$empName."</td>";
            $arr[$empName]['printed'] = 'yes';
        }
        echo "<td>".$sal[$i]."</td>";
        echo "</tr>";
    }
    echo "</table>";

Tối ưu hóa mã:

Bây giờ chúng ta có thể kết hợp tính toán rowspan và tìm nạp dữ liệu mysql. Bởi vì trong quá trình lưu dữ liệu đã tìm nạp trong mảng, chúng ta có thể tính toán sải hàng. Vì vậy, mã cuối cùng của chúng tôi:

<!DOCTYPE html>
<html>
    <head>
        <style>
            table tr td, table tr th{
                border: black 1px solid;
                padding: 5px;
            }
        </style>
    </head>
    <body>
        <?php
        # connect to mysql server
        # and select the database, on which
        # we will work.
        $conn = mysql_connect('', 'root', '');
        $db   = mysql_select_db('test');

        # Query the data from database.
        $query  = 'SELECT * FROM test_work ORDER BY ename, sal';
        $result = mysql_query($query);

        # $arr is array which will be help ful during 
        # printing
        $arr = array();

        # Intialize the array, which will 
        # store the fetched data.
        $sal = array();
        $emp = array();

        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
        #     data saving and rowspan calculation        #
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#

        # Loop over all the fetched data, and save the
        # data.
        while($row = mysql_fetch_assoc($result)) {
            array_push($emp, $row['ename']);
            array_push($sal, $row['sal']);

            if (!isset($arr[$row['ename']])) {
                $arr[$row['ename']]['rowspan'] = 0;
            }
            $arr[$row['ename']]['printed'] = 'no';
            $arr[$row['ename']]['rowspan'] += 1;
        }


        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        #        DATA PRINTING             #
        #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
        echo "<table cellspacing='0' cellpadding='0'>
                <tr>
                    <th>Ename</th>
                    <th>Sal</th>
                </tr>";


        for($i=0; $i < sizeof($sal); $i++) {
            $empName = $emp[$i];
            echo "<tr>";

            # If this row is not printed then print.
            # and make the printed value to "yes", so that
            # next time it will not printed.
            if ($arr[$empName]['printed'] == 'no') {
                echo "<td rowspan='".$arr[$empName]['rowspan']."'>".$empName."</td>";
                $arr[$empName]['printed'] = 'yes';
            }
            echo "<td>".$sal[$i]."</td>";
            echo "</tr>";
        }
        echo "</table>";
        ?>
    </body>
</html>

Kết quả:



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Truy vấn chọn chuỗi kết thúc bằng ký tự nhất định

  2. SQL UPDATE tất cả các giá trị trong một trường có chuỗi nối thêm CONCAT không hoạt động

  3. Có quy ước đặt tên cho MySQL không?

  4. Làm cách nào để giải quyết tình trạng Overrun ngăn xếp luồng mysql?

  5. Ví dụ về TIMESTAMPDIFF () - MySQL