随手记录下TP5的UNION

Test1:
//自动过滤重复的name值
public function test(){
	$name=Db::field('name')
		  ->table('user_address')
		  ->union('SELECT name FROM pid')
		  ->union('SELECT name FROM ceshi')
		  ->select();
    dump($name);
}

//输出:
array(7) {
  [0] => array(1) {
    ["name"] => string(6) "曾某"    //user_address
  }
  [1] => array(1) {
    ["name"] => string(5) "test1"    //pid
  }
  [2] => array(1) {
    ["name"] => string(4) "test"    //pid
  }
  [3] => array(1) {
    ["name"] => string(3) "ymk"    //ceshi
  }
  [4] => array(1) {    
    ["name"] => string(6) "ymkk"    //ceshi
  }
  [5] => array(1) {
    ["name"] => string(5) "test3"    //ceshi
  }
  [6] => array(1) {
    ["name"] => string(5) "test2"    //ceshi
  }
}


Test2:
//不过滤重复,显示所有的name值
public function test(){
	$name=Db::field('name')
		  ->table('user_address')
		  ->union('SELECT name FROM pid')
		  ->union('SELECT name FROM ceshi',true)    //最后一个union加上true
		  ->select();
    dump($name);
}

Test3:
//显示单表的name值并且过滤重复
public function test(){
	$name=Db::field('name')
		  ->table('user_address')
		  ->union('SELECT name FROM user_address')   
		  ->select();
    dump($name);
}
//输出:
array(1) {
  [0] => array(1) {
    ["name"] => string(6) "曾某"
  }
}
//显示单表的name值并且过滤重复还可使用distinct
$name=Db::table('user_address')->distinct(true)->field('name')->select(); 

Test4:
//结合Query 可传参
public function test(){
	$status=1;
    $zh=111111;
	$name=Db::field('name')
		  ->table('user_address')->where('status',$status)
		  ->union(function($query)use ($status,$zh){    //use 传参
		        $query->field('name')->table('pid')->where(array('status'=>$status,'zh'=>$zh));
		    })
		  ->union(function($query,$level=2){
		      	$query->field('name')->table('ceshi')->where('level',$level);
		    })
		  ->select();
    dump($name);
}

 

你可能感兴趣的:(PHP)