上一篇《》中介绍了Medoo的WHERE语法,本篇将要对Select方法进行说明。Select API主要用于设定提取数据的目标字段。
选取方法:Select
从数据库中选取数据。
select($table, $columns, $where)//table [string]: 表名//columns [string/array]: 将要提取的数据的目标字段//where (可选) [array]: 过滤记录的WHERE子句 select($table, $join, $columns, $where)join [array]: 表连接相关的表名。如果不需要连接,则忽略它。
返回值: [array]
提示:您可以使用“*”为列参数,来获取所有的列,但为了提高性能,提供目标列的话要好得多。
$database = new medoo("my_database"); $datas = $database->select("account", [ "user_name", "email"], [ "user_id[>]" => 100]); // $datas = array(// [0] => array(// "user_name" => "foo",// "email" => "foo@bar.com"// ),// [1] => array(// "user_name" => "cat",// "email" => "cat@dog.com"// )// ) foreach($datas as $data){ echo "user_name:" . $data["user_name"] . " - email:" . $data["email"] . "";} // 选取所有列$datas = $database->select("account", "*"); // 选取单列user_name$datas = $database->select("account", "user_name"); // $datas = array(// [0] => "foo",// [1] => "cat"// ) // [表连接]// SQL-JOIN子句能够把两个表之间的行绑定在一起。Medoo为JOIN子句提供了简单的语法。 // [>] == LEFT JOIN// [<] == RIGH JOIN// [<>] == FULL JOIN// [><] == INNER JOIN $database->select("post", [ // 这是相关联的表的参数,它表明了你想要进行连接的表之间的关联性。 // post.author_id 等于 account.user_id "[>]account" => ["author_id" => "user_id"], // post.user_id 等于 album.user_id // 如果两个表中的字段名是相同的,那么你可以使用以下这种快捷的方式来声明关联性。 "[>]album" => "user_id", // [post.user_id 等于 photo.user_id, 并且 post.avatar_id 等于 photo.avatar_id] // 和上面一样,在各个表中的字段名都是相同的 "[>]photo" => ["user_id", "avatar_id"]], [ "post.post_id", "post.title", "account.city"], [ "post.user_id" => 100, "ORDER" => "post.post_id DESC", "LIMIT" => 50]); // SELECT// `post`.`post_id`,// `post`.`title`,// `account`.`city`// FROM `post`// LEFT JOIN `account` ON `post`.`author_id` = `account`.`user_id`// LEFT JOIN `album` USING (`user_id`)// LEFT JOIN `photo` USING (`user_id`, `avatar_id`)// WHERE// `post`.`user_id` = 100// ORDER BY `post`.`post_id` DESC// LIMIT 50 //[列的别名 - 自Medoo 0.9.1起支持]// 你可以使用列别名作为一个新的列名,用于替代原来的。// 这在表连接的时候,用来防止列名冲突非常有用。$data = $database->select("account", [ "user_id", "nickname(my_nickname)"], [ "LIMIT" => 20]); // $data = array(// [0] => array(// "user_id" => "1",// "my_nickname" => "foo"// ),// [1] => array(// "user_id" => "2",// "my_nickname" => "bar"// )// ) $data = $database->select("post", [ "[>]account" => "user_id",], [ "post.user_id(post_user_id)", "account.user_id(account_user_id)"], [ "LIMIT" => 20]); // $data = array(// [0] => array(// "post_user_id" => "1",// "account_user_id" => "321"// ),// [1] => array(// "post_user_id" => "2",// "account_user_id" => "322"// )// )
原文标题:
原文链接: