sql连接查询

Posted 倒霉的大熊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql连接查询相关的知识,希望对你有一定的参考价值。

连接数据库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连接查询的主要内容,如果未能解决你的问题,请参考以下文章

在 Rails 上为连接、限制、选择等(不是条件)的 SQL 片段安全地转义字符串

sql [SQL查询片段]用于在命令行或通过R和其他工具使用SQL的快速代码段#tags:sql,R,text processing,命令li

sql mysql查询/ db片段

MyBatis查询mysql数据返回null

java如何实现sql连接和查询的代码?

SSM-MyBatis-05:Mybatis中别名,sql片段和模糊查询加getMapper