選取方法:Select API-Medoo使用指南

上一篇《WHERE語法-Medoo使用指南》中介紹了Medoo的WHERE語法,本篇將要對Select方法進行說明。Select API主要用於設定提取數據的目標字段。php

選取方法:Select html

從數據庫中選取數據。數據庫

select($table, $columns, $where)
//table [string]: 表名
//columns [string/array]: 將要提取的數據的目標字段
//where (可選) [array]: 過濾記錄的WHERE子句
 
select($table, $join, $columns, $where)
join [array]: 錶鏈接相關的表名。若是不須要鏈接,則忽略它。


返回值: [array]post

 提示:您能夠使用「*」爲列參數,來獲取全部的列,但爲了提升性能,提供目標列的話要好得多。性能

$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"] . "<br/>";
}
 
// 選取全部列
$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"
// 	)
// )


原文標題:選取方法:Select API-Medoo使用指南spa

原文連接:http://loiy.net/post/572.html.net

相關文章
相關標籤/搜索