码迷,mamicode.com
首页 > 数据库 > 详细

sql连接查询

时间:2018-09-08 18:57:26      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:mys   eve   center   查询   edit   size   join   mysq   enter   

连接数据库PDO

$user = "root";  //数据库连接账号

$pass = "root";  //数据库连接密码

$dbname = "test";		//数据库名

try {
    $db = new PDO("mysql:host=localhost;dbname=$dbname", $user, $pass);  //连接数据库
	echo "数据库连接成功";
} catch (PDOException $e) {
	echo "数据库连接失败";
}

表一:user表

 idname 姓名sex 性别age 年龄
1 fan 0 18
2 jack 0 25
3 xiaoming 0 33
4 laowang 1 50
5 julia 0 22
6 pangda 1

53

表二:user_Identity表

ididentity_number 身份号码
1 111
2 222
3 333
4 444
5 555
6 666

1、内连接(Inner Join)

$sql = "select * from user as a inner join user_identity as b on a.id = b.id"; //内连接user和user_identity表,as 起别名:user代表a,user_identity代表b

//$sql = "select * from user inner join user_identity on user.id = user_identity.id"; // 效果同上

//$sql = "select a.id,a.name,b.identity_number from user as a inner join user_identity as b on a.id = b.id";  //select 和 from 之间的意思是 - 输出a表的id字段,输出a表的name字段,输出b表的identity_number;

$data = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);

print_r ($data);

输出:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => fan
            [sex] => 0
            [age] => 18
            [identity_number] => 111
        )

    [1] => Array
        (
            [id] => 2
            [name] => jack
            [sex] => 0
            [age] => 25
            [identity_number] => 222
        )

    [2] => Array
        (
            [id] => 3
            [name] => xiaoming
            [sex] => 0
            [age] => 33
            [identity_number] => 333
        )

    [3] => Array
        (
            [id] => 4
            [name] => laowang
            [sex] => 1
            [age] => 50
            [identity_number] => 444
        )

    [4] => Array
        (
            [id] => 5
            [name] => julia
            [sex] => 0
            [age] => 22
            [identity_number] => 555
        )

    [5] => Array
        (
            [id] => 6
            [name] => pangda
            [sex] => 1
            [age] => 53
            [identity_number] => 666
        )

)

 

sql连接查询

标签:mys   eve   center   查询   edit   size   join   mysq   enter   

原文地址:https://www.cnblogs.com/fan-bk/p/9609990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!