联合查询及使用函数


关于联合查询及使用函数的方法

LEFT JOIN, RIGHT JOIN

所有的查询语法最终都会生成以下的SQL:

SELECT ... FROM 表名 WHERE ...

表名都位于FROMWHERE之间, 在CP中, 要实现LEFT JOINRIGHT JOIN, 简洁风格的查询写法如下:

$this->link->getAll('table t LEFT JOIN table_second ts ON t.id=ts.tid', '*', array(
    't.id' =>  1
));

链式查询也一样:

$this->link->select('*')
	->from('table t LEFT JOIN table_second ts ON t.id=ts.tid')
	->where(array('t.id' => 1))
	->stmt()->fetchAll();

COUNT

要在字段中使用函数的原生SQL语句如下

SELECT count(*) FROM table WHERE ...

同上CP中的简洁风格查询写法如下:

$this->link->get(table, 'count(*)', array(....))

链式风格的写法如下:

$this->link->select('count(*)')
	->from(table)->stmt()->fetchAll();

手动使用参数绑定

更复杂的情况下, 可以使用手写SQL

$sql = "select t.*, ts.* from ( select * from table where uid = ?) u left join table_extends ts on t.id=ts.tid"

$this->link->prepare($sql)->exec(array(1))->stmtFetch(true);

FIND IN SET

mysql的where还支持FIND_IN_SET, 用于排序

REGEXP

在mysql的where中使用正则表达式

INSTR

mysql的where专有函数