如何组合2个SQL查询以获得1个结果

时间:2017-03-10 14:49:11

标签: mysql database codeigniter activerecord

SELECT users.name, users.registrationdate, users.city, users.status
FROM users, referrals
WHERE users.username= referrals.referrals AND referrals.username='user_name'

SELECT adearning, reffearning
FROM earnings WHERE usersname='user_name33'

如何将这两个查询组合起来,就好像第一个查询条件不匹配且不运行..然后第二个查询应运行并在条件匹配时返回一些值

1 个答案:

答案 0 :(得分:0)

试试这个

$query1 = $this->db->query("SELECT users.name, users.registrationdate, users.city, users.status 
                            FROM users, referrals 
                            WHERE users.username = referrals.referrals AND referrals.username='user_name'")
$result1 = $query1->result_array();


$query2 = $this->db->query("SELECT adearning, reffearning FROM earnings WHERE usersname='user_name33' ")
$result2 = $query2->result_array();


$dataArray = array_merge($result1, $result2);

如果要检查结果,行末尾添加此

print_r($dataArray);die;
  

在此,它将在一个数组中打印所有这些

示例

$result1 = array(
    '0' => 'sjhccsd', 
    '1' => 'ddd', 
    '2' => 'df', 
    '3' => 'dfd', 
    );

$result2 = array(
    '0' => 'sjhccsd', 
    '1' => 'ddd', 
    '2' => 'df', 
    '3' => 'dfd', 
    );


$dataArray = array_merge($result1, $result2);

print_r($dataArray);

输出Array ( [0] => sjhccsd [1] => ddd [2] => df [3] => dfd [4] => sjhccsd [5] => ddd [6] => df [7] => dfd )