php数据查询之基础查询

---恢复内容开始---

数据查询语言(Data Query Language)

基本查询

  • 语法形式:
    select [all | distinct ] 字段或者表达式列表 [from子句] [where子句] [group by 子句] [having 子句] [order by 子句] [limit 子句]
  • 解释说明
    • select 从“数据源”中,找出(取出)数据。
      •  “数据源通常指“表”,也可以是“直接数据”或者函数返回结果。示例:
        mysql> select 5, 8*9, now();
        +---+-----+---------------------+
        | 5 | 8*9 | now()               |
        +---+-----+---------------------+
        | 5 |  72 | 2018-10-24 15:36:07 |
        +---+-----+---------------------+
        1 row in set (0.00 sec)
      • 也可以加字段(别)名:
        mysql> select 5 as num, 8*9 as multi, now() as time;
        +-----+-------+---------------------+
        | num | multi | time                |
        +-----+-------+---------------------+
        |   5 |    72 | 2018-10-24 15:40:35 |
        +-----+-------+---------------------+
        1 row in set (0.00 sec)
      • 不能使用“表”的字段而没有from 子句
        mysql> select id;
        ERROR 1054 (42S22): Unknown column 'id' in 'field list'
    • [all | distinct]
      • 用于设定所select的数据是否允许出现重复行
      • all:允许出现
      • distinct:不允许出现---就是所谓的“消除重复行”
    • from 子句
      • 指定数据的来源,其实就是“表”。可以是单个“表”,也可以是多个“表”,用逗号隔开。
        mysql> select id, title, NO, context from sqltest, set_test;
        +----+--------+----+---------+
        | id | title  | NO | context |
        +----+--------+----+---------+
        |  1 | 第一个 |  1 | aa      |
        |  1 | 第一个 |  2 | aa,cc   |
        |  2 | 第二个 |  1 | aa      |
        |  2 | 第二个 |  2 | aa,cc   |
        |  3 | 第三个 |  1 | aa      |
        |  3 | 第三个 |  2 | aa,cc   |
        +----+--------+----+---------+
        6 rows in set (0.00 sec)
        
        mysql> select * from sqltest;
        +----+--------+----------------------------------------------------------+
        | id | title  | content                                                  |
        +----+--------+----------------------------------------------------------+
        |  1 | 第一个 | 这是ID=1的数据
        1111111111111111111111111111111111111111 |
        |  2 | 第二个 | 这是ID=2的数据
        2222222222222222222222222222222222222222 |
        |  3 | 第三个 | 这是ID=3的数据
        3333333333333333333333333333333333333333 |
        +----+--------+----------------------------------------------------------+
        3 rows in set (0.00 sec)
        
        mysql> select * from set_test;
        +----+---------+
        | NO | context |
        +----+---------+
        |  1 | aa      |
        |  2 | aa,cc   |
        +----+---------+
        2 rows in set (0.00 sec)
    • where 子句
      • 相当于php或者js中的if语句-条件判断语句,最终结果为布尔值(true/false)。
      • 常用运算符
        1. 算术运算符:+  -  *  /  %
        2. 比较运算符:
          • >  >=  <  <=  =(等于)  <>(不等于)-标准的sql语言
          • ==(等于)  !=(不等于)--mysql扩展
        • 逻辑运算符:and(与)  or(或)  no(非)
          mysql> select * from production where pro_id<5 and price-300<3000;
          +--------+-----------------------------------+------+-------+-------+--------+
          | pro_id | name                              | type | price | brand | origin |
          +--------+-----------------------------------+------+-------+-------+--------+
          |      1 | 康佳(KONKA)42英寸全高清液晶电视 |    1 |  1999 | 康佳  | 深圳   |
          |      2 | 索尼(SONY)4G手机(黑色)        |    2 |  3238 | 索尼  | 深圳   |
          +--------+-----------------------------------+------+-------+-------+--------+
          2 rows in set (0.00 sec)
          
          mysql> select * from production;
          +--------+-----------------------------------+------+-------+-------+--------+
          | pro_id | name                              | type | price | brand | origin |
          +--------+-----------------------------------+------+-------+-------+--------+
          |      1 | 康佳(KONKA)42英寸全高清液晶电视 |    1 |  1999 | 康佳  | 深圳   |
          |      2 | 索尼(SONY)4G手机(黑色)        |    2 |  3238 | 索尼  | 深圳   |
          |      3 | 海信(Hisense)55英寸智能电视     |    1 |  4199 | 海信  | 青岛   |
          |      4 | 联想(Lenovo)14.0英寸笔记本电脑  |    3 |  5499 | 联想  | 北京   |
          |      5 | 索尼(SONY)13.3英寸触控超极本    |    3 | 11499 | 索尼  | 天津   |
          |      6 | 索尼(SONY)60英寸全高清液晶电视  |    1 |  6999 | 索尼  | 北京   |
          |      7 | 联想(Lenovo)12.0英寸笔记本电脑  |    3 |  2999 | 联想  | 北京   |
          |      8 | 联想 双卡双待3G手机               |    2 |   988 | 联想  | 北京   |
          |      9 | 惠普(HP)黑白激光打印机          |    3 |  1169 | 惠普  | 天津   |
          +--------+-----------------------------------+------+-------+-------+--------+
          9 rows in set (0.00 sec)
      • 布尔值和空值判断
        • 布尔值(true/false):范围,整数。实际就是tinyint(1)的数字,0为true,非零为false
          • xx is true
          • xx is false
        • 空值(null)
          • xx is null
          • xx is not null
      • 常用语法
        • between 语法
          • xx between 值1 and 值2 
          • xx 值介于值1和值2之间(包含值1和值2),相当于 值1<=xx and xx <=值2
        • in 语法
          • xx in(值1 , 值2, ...)
          • 字段值xx等于其中任何一个都成立,相当于 xx=值1 or xx=值2 ...
        • like 语法(模糊查找)
          • 形式: like '要查找的字符'---范围为字符型字段
          • 说明
            • like语法用于多字符类型的字段进行字符匹配
            • 要查找的字符中有2个特殊的字符%、_
              • %--代表任意多个任意字符
              • '_'代表单个的任意字符
          • 要使用字符'%'和'_',需要使用转义字符'\'
    • group by 分组子句   
      mysql> select * from production;
      +--------+-----------------------------------+------+-------+-------+--------+
      | pro_id | name                              | type | price | brand | origin |
      +--------+-----------------------------------+------+-------+-------+--------+
      |      1 | 康佳(KONKA)42英寸全高清液晶电视 |    1 |  1999 | 康佳  | 深圳   |
      |      2 | 索尼(SONY)4G手机(黑色)        |    2 |  3238 | 索尼  | 深圳   |
      |      3 | 海信(Hisense)55英寸智能电视     |    1 |  4199 | 海信  | 青岛   |
      |      4 | 联想(Lenovo)14.0英寸笔记本电脑  |    3 |  5499 | 联想  | 北京   |
      |      5 | 索尼(SONY)13.3英寸触控超极本    |    3 | 11499 | 索尼  | 天津   |
      |      6 | 索尼(SONY)60英寸全高清液晶电视  |    1 |  6999 | 索尼  | 北京   |
      |      7 | 联想(Lenovo)12.0英寸笔记本电脑  |    3 |  2999 | 联想  | 北京   |
      |      8 | 联想 双卡双待3G手机               |    2 |   988 | 联想  | 北京   |
      |      9 | 惠普(HP)黑白激光打印机          |    3 |  1169 | 惠普  | 天津   |
      +--------+-----------------------------------+------+-------+-------+--------+
      9 rows in set (0.01 sec)
      mysql> select * from production group by brand;
      +--------+-----------------------------------+------+-------+-------+--------+
      | pro_id | name                              | type | price | brand | origin |
      +--------+-----------------------------------+------+-------+-------+--------+
      |      1 | 康佳(KONKA)42英寸全高清液晶电视 |    1 |  1999 | 康佳  | 深圳   |
      |      9 | 惠普(HP)黑白激光打印机          |    3 |  1169 | 惠普  | 天津   |
      |      3 | 海信(Hisense)55英寸智能电视     |    1 |  4199 | 海信  | 青岛   |
      |      2 | 索尼(SONY)4G手机(黑色)        |    2 |  3238 | 索尼  | 深圳   |
      |      4 | 联想(Lenovo)14.0英寸笔记本电脑  |    3 |  5499 | 联想  | 北京   |
      +--------+-----------------------------------+------+-------+-------+--------+
      5 rows in set (0.00 sec)
      • 形式:group by 字段1 排序方式1, 字段2 排序方式 2 ...
        • 通常只进行一个字段的分组   
      • 含义
        • 分组?以某个字段的值为“依据”,分到不同的“类别”中。
      • 结果
        • 分组结果只能是“组”---没有数据本身的个性
        • 分组结果很“可能”死去很多特性,比如:序号,名字等等
        • 实际上,分组结果中通常只剩下以“组”为单位的整体信息,如:分组依据本身,成员个数,总和,最大值,最小值,平均值
      • 上述结果反映在select 语句中为“字段或者表达式部分”
        mysql> select brand, count(*) as counts, sum(price) as amount, avg(price) as avg
        Price, max(price) as maxPrice from production group by brand;
        +-------+--------+--------+-------------------+----------+
        | brand | counts | amount | avgPrice          | maxPrice |
        +-------+--------+--------+-------------------+----------+
        | 康佳  |      1 |   1999 |              1999 |     1999 |
        | 惠普  |      1 |   1169 |              1169 |     1169 |
        | 海信  |      1 |   4199 |              4199 |     4199 |
        | 索尼  |      3 |  21736 | 7245.333333333333 |    11499 |
        | 联想  |      3 |   9486 |              3162 |     5499 |
        +-------+--------+--------+-------------------+----------+
        5 rows in set (0.00 sec)
      • 在分组查询中,基本上依赖于一下几个函数(聚合函数,统计函数)
        • sum(字段x)--分组后字段x的总和
        • max(字段x)--分组后字段x中的最大值
        • min(字段x)--分组后字段x中的最小值
        • avg(字段x)--分组后字段x中的平均值
        • count(*)--分组内成员数
      • 默认分组查询结果正序显示,想要倒序显示,需在分组依据后加关键字“desc”
        mysql> select brand, count(*) as counts, sum(price) as amount, avg(price) as avg
        Price, max(price) as maxPrice from production group by brand desc;
        +-------+--------+--------+-------------------+----------+
        | brand | counts | amount | avgPrice          | maxPrice |
        +-------+--------+--------+-------------------+----------+
        | 联想  |      3 |   9486 |              3162 |     5499 |
        | 索尼  |      3 |  21736 | 7245.333333333333 |    11499 |
        | 海信  |      1 |   4199 |              4199 |     4199 |
        | 惠普  |      1 |   1169 |              1169 |     1169 |
        | 康佳  |      1 |   1999 |              1999 |     1999 |
        +-------+--------+--------+-------------------+----------+
        5 rows in set (0.00 sec)
      • 如果是2个字段或者以上的分组,其实是在前一分组组内,在依据后一分组依据进行分组。

        mysql> select brand, origin, count(*) as counts from production group by brand,
        origin;
        +-------+--------+--------+
        | brand | origin | counts |
        +-------+--------+--------+
        | 康佳  | 深圳   |      1 |
        | 惠普  | 天津   |      1 |
        | 海信  | 青岛   |      1 |
        | 索尼  | 北京   |      1 |
        | 索尼  | 天津   |      1 |
        | 索尼  | 深圳   |      1 |
        | 联想  | 北京   |      3 |
        +-------+--------+--------+
        7 rows in set (0.00 sec)
    • having 子句
      • having 子句和where 子句概念相同,不同之处在于:
        • where 子句是以字段为“判断条件”
        • having 子句是以group by 后“组”数据为“判断条件”
        • 既having 后 不能跟字段,如:having priice >3000.但是可以跟“组”数据或者“组”数据别名,包含分组依据本身,如:having avg(price) > 3000。
    • oder by 子句
      • 形式:
        • oder by 字段1 排序方式1, 字段2 排序方式2, ...
      • 说明:
        • 是对前面数据(where 子句,from 子句, group by 子句, having 子句等)按照某个字段进行大小排序,有
        • 2中排序方式:
          • 正序:ASC(默认值)
          • 倒叙:DESC
      • 多种方式排序指在前一排序的相同字段内按照后一字段大小在进行排序
        mysql> select name,origin,price from production order by origin,price desc;
        +-----------------------------------+--------+-------+
        | name                              | origin | price |
        +-----------------------------------+--------+-------+
        | 索尼(SONY)60英寸全高清液晶电视  | 北京   |  6999 |
        | 联想(Lenovo)14.0英寸笔记本电脑  | 北京   |  5499 |
        | 联想(Lenovo)12.0英寸笔记本电脑  | 北京   |  2999 |
        | 联想 双卡双待3G手机               | 北京   |   988 |
        | 索尼(SONY)13.3英寸触控超极本    | 天津   | 11499 |
        | 惠普(HP)黑白激光打印机          | 天津   |  1169 |
        | 索尼(SONY)4G手机(黑色)        | 深圳   |  3238 |
        | 康佳(KONKA)42英寸全高清液晶电视 | 深圳   |  1999 |
        | 海信(Hisense)55英寸智能电视     | 青岛   |  4199 |
        +-----------------------------------+--------+-------+
        9 rows in set (0.00 sec)
        
        mysql> select name,origin,price from production order by origin,price;
        +-----------------------------------+--------+-------+
        | name                              | origin | price |
        +-----------------------------------+--------+-------+
        | 联想 双卡双待3G手机               | 北京   |   988 |
        | 联想(Lenovo)12.0英寸笔记本电脑  | 北京   |  2999 |
        | 联想(Lenovo)14.0英寸笔记本电脑  | 北京   |  5499 |
        | 索尼(SONY)60英寸全高清液晶电视  | 北京   |  6999 |
        | 惠普(HP)黑白激光打印机          | 天津   |  1169 |
        | 索尼(SONY)13.3英寸触控超极本    | 天津   | 11499 |
        | 康佳(KONKA)42英寸全高清液晶电视 | 深圳   |  1999 |
        | 索尼(SONY)4G手机(黑色)        | 深圳   |  3238 |
        | 海信(Hisense)55英寸智能电视     | 青岛   |  4199 |
        +-----------------------------------+--------+-------+
        9 rows in set (0.00 sec)
    • limit 子句
      • 形式:
        • limit [起始行号]start, [要取出的行数]rows;
      • 说明:
        • 前面所取得的数据,对之取“局部若干数据”。
        • 起始行号:start 第一行为0,默认值,省略则取默认值
        • 要取出的行数:如果数据记录不足,则取出当前数据行
      • 此子句很常用。比如:网页中很常见的需求---分页
    • 实用示例:
      • delete-- 删除指定行
      • limit-----分页显示
      • php代码:
        <?php
            /*定义表
            create table user_list(
                id int(10) not null primary key auto_increment,
                user_name varchar(30) not null,
                user_pass char(32) not null,
                user_age tinyint(1) unsigned,
                user_edu enum('小学', '初中', '高中' , '大专', '本科', '本科以上'),
                use_interest set('篮球', '足球', '跑步', '读书', '画画', '旅游'),
                user_nativePlac
            
            e enum('华北', '华中', '华南', '东北', '西北', '华东')
                );*/
            $conn = mysqli_connect("localhost", "root", "root", "test1"); 
            if (!$conn) 
            { 
                die("连接错误: " . mysqli_connect_error()); 
            } 
        
            if($_POST){
                
            
                $user_name = $_POST['user_name'];
                $user_pass = $_POST['user_pass'];
                $user_age = $_POST['user_age'];
                $user_edu = $_POST['user_edu'];//注意user_edu数组
                $user_interest = $_POST['user_interest'];
                $user_nativePlace = $_POST['user_nativePlace'];
                
                if(empty($user_name)||empty($user_pass)){
                    $errMsg = "发生错误:用户名/密码不能为空!";
                }else {
                    //对爱好/$user_interest[]做求和出来
                    $user_interest_sum = array_sum($user_interest);
                    $sql_add = "insert into user_list(user_name, user_pass, user_age, user_edu, user_interest, user_nativePlace, reg_time)values";
                    $sql_add .= "('$user_name', '$user_pass', $user_age, $user_edu, $user_interest_sum, $user_nativePlace, now());";
                    echo $sql_add."<br />";
                    $result_add = mysqli_query($conn, $sql_add);
                    if($result_add){
                        $errMsg = "插入成功<hr />";
                    }else {
                        $errMsg = "插入失败<hr />";
                    }
                }
            }else {
                    
            
        
                if(($_GET)){
                    if(!empty($_GET['ID'])){
                        $id = $_GET['ID'];
                        $sql_delrec = "select * from user_list where id = $id";
                        $sql_del = "delete from user_list where id = $id";
                        echo "<hr />";
                        $result_delrec = mysqli_query($conn, $sql_delrec);
                        echo "记录:";
                        $out_del = mysqli_fetch_array($result_delrec);
                        echo $out_del['id']." ".$out_del['user_name']." ".$out_del['user_pass']." ".$out_del['user_age']." ".$out_del['user_edu']." ".$out_del['user_interest']." ".$out_del['user_nativePlace']." ".$out_del['reg_time']."<br />";
                        
                        $result_del = mysqli_query($conn, $sql_del);
                        if($result_del){
                            echo "删除成功<hr />";
                        }else{
                            echo "删除失败<hr />";
                        }
                    }
                    if(!empty($_GET['page'])){
                        $page = $_GET['page'];
                    }else {
                        $page = 0;
                    }
                    
                }
                else {
                
            }
            }
        ?>
        
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
        <head>
            <meta http-equiv="Content-Type" content="text/html;charset=utf8" />
            <title>Apache、PHP、MySQL可运行测试</title>
            <meta name="keywords" content="关键字列表" />
            <meta name="description" content="网页描述" />
            <link rel="stylesheet" type="text/css" href="" />
            <style type="text/css">
                .special {
                    color: red;
                }
        
                span {
                    font: 700 13px/13px "microsoft yahei";
                    margin-right: 5px;
                }
            </style>
            <script type="text/javascript"></script>
        </head>
        <body>
            <div>
            <?php
                if(!empty($errMsg)){
                    echo $errMsg;
                } 
            ?>
            </div>
            <form action="" method="post">
                <span>用户名:</span><input type="text" name="user_name" /><br />
                <span>密码&nbsp;&nbsp;:</span>   <input type="password" name="user_pass" /><br />
                <span>年龄&nbsp;&nbsp;:</span>   <input type="text" name="user_age" /><br />
                <span>学历&nbsp;&nbsp;:</span>  <select name="user_edu" id="">
                            <option value="1">小学</option>
                            <option value="2">初中</option>
                            <option value="3">高中</option>
                            <option value="4">大专</option>
                            <option value="5">本科</option>
                            <option value="6">本科以上</option>
                        </select><br />
                <span>爱好&nbsp;&nbsp;:</span> 
                        <input type="checkbox" name="user_interest[]" value="1="/>篮球
                        <input type="checkbox" name="user_interest[]" value="2" />足球
                        <input type="checkbox" name="user_interest[]" value="4" />跑步
                        <input type="checkbox" name="user_interest[]" value="8" />读书
                        <input type="checkbox" name="user_interest[]" value="16" />画画
                        <input type="checkbox" name="user_interest[]" value="32" />旅游<br />
                <span>籍贯&nbsp;&nbsp;:</span>    <input type="radio" name="user_nativePlace" value="1" />华北
                        <input type="radio" name="user_nativePlace" value="2" />华中
                        <input type="radio" name="user_nativePlace" value="3" />华南
                        <input type="radio" name="user_nativePlace" value="4" />华西
                        <input type="radio" name="user_nativePlace" value="5" />东北
                        <input type="radio" name="user_nativePlace" value="6" />西北<br />
                <input type="submit" value="提交" /><br />    
            </form>
        
            <?php
                
                
                echo "<hr />";
                $pageRecords = 3;
                
                $start = $page*$pageRecords;
                $sql_dis ="select * from user_list limit $start,$pageRecords";
                $result_dis = mysqli_query($conn ,$sql_dis);
                $filename = $_SERVER['SCRIPT_NAME'];
                
                echo "<table border = 1 >";
                echo "<tr>";
                echo "<th>"."id"."</th>";
                echo "<th>"."user_name"."</th>";
                echo "<th>"."user_pass"."</th>";
                echo "<th>"."user_age"."</th>";
                echo "<th>"."user_edu"."</th>";
                echo "<th>"."user_interest"."</th>";
                echo "<th>"."user_nativePlace"."</th>";
                echo "<th>"."reg_time"."</th>";
                echo "<th>"."action"."</th>";
                echo "</tr>";
                
                
                while ($res = mysqli_fetch_array($result_dis)) {
                    echo "<tr>";
                    echo "<td>".$res['id']."</td>";
                    echo "<td>".$res['user_name']."</td>";
                    echo "<td>".$res['user_pass']."</td>";
                    echo "<td style='color:red;'>".$res['user_age']."</td>";
                    echo "<td>".$res['user_edu']."</td>";
                    echo "<td>".$res['user_interest']."</td>";
                    echo "<td>".$res['user_nativePlace']."</td>";
                    echo "<td>".$res['reg_time']."</td>";
                    echo "<td>";
                    echo "[<a href='$filename?ID={$res['id']}'>删除</a>]";
                    echo "</td>";
                    echo "</tr>";
                }
                echo "</table><br />";
                
                for($i = 0; $i <=10; $i++){
                    echo "<a href='$filename?page=$i'>".($i+1)."</a>   ";
                }
                echo "<br />";
            ?>
        </body>
        </html>
      • 网页效果:
        • 第一页
        • 第二页

连接查询

子查询

联合查询

---恢复内容结束---

猜你喜欢

转载自www.cnblogs.com/gaogzhen/p/9844800.html