在查询的sql之间添加UNION不为空

时间:2018-09-24 07:05:07

标签: php sql

我全部。我有一系列查询

$queries = [
    $sql1,
    $sql2,
    $sql3,
    $sql4
];

我想要一个PHP函数,可以在它们之间自动连接“ UNION”。例如,如果所有四个查询都在那里,则应返回类似

的内容
$sql1 . ' UNION ' . $sql2 . ' UNION ' . $sql3 . ' UNION ' . $sql4;

如果$sql2$sql3为空,则应返回

$sql1 . ' UNION ' . $sql4

当前我正在使用此功能

function concatenate_queries($arr){
    $final_query = "";
    foreach ($arr as $q){
        $final_query = $q . ' UNION ';
    }
    return $final_query;
}

但是它不会产生正确的输出。

编辑

查询示例

<pre>Array
(
    [0] => SELECT 'deposit' as t_type, tx_amount as total, tx_fee as fee, tx_net as amount, tx_currency as currency, tx_exchange_rate as ex_rate, transactionTime as created , paymentId as trax_id,  'payments' as tb, 'completed' as status  FROM payments WHERE userId='51' AND (DATE(transactionTime) BETWEEN '2018-08-24' AND '2018-09-24')
UNION
SELECT 'deposit' as t_type, amount as total, 0 as fee, amount as amount, 'EUR' as currency, 1 as ex_rate,  created, id as trax_id,  'coinbase_deposits' as tb, 'completed' as status FROM coinbase_deposits WHERE asset='EUR' AND userId='51' AND (DATE(created) BETWEEN '2018-08-24' AND '2018-09-24')

    [1] => SELECT 'buy' as t_type, total_amount as total, fee_coinbase as fee, subtotal as amount, total_amount_currency as currency, 1 as ex_rate,  created, id as trax_id, 'coinbase_transactions' as tb,status FROM coinbase_transactions
WHERE wallet='EUR' AND userId='51' AND resource='sell' AND (DATE(created) BETWEEN '2018-08-24' AND '2018-09-24') 

    [2] => SELECT 'withdraw' as t_type, amount as total, 0 as fee, amount, 'gbp' as currency , 1 as ex_rate, created, id as trax_id, 'refunds' as tb, 'completed' as status FROM refunds WHERE user_id='51' AND (DATE(created) BETWEEN '2018-08-24' AND '2018-09-24') 
UNION
 SELECT 'withdraw' as t_type, amount as total_amount, 0 as fee, amount,  'gbp' as currency , 1 as ex_rate, created, id as trax_id, 'manual_refunds' as tb,  CASE WHEN (status=0) THEN 'pending' ELSE 'completed' END as status FROM manual_refunds WHERE user_id='51' AND (DATE(created) BETWEEN '2018-08-24' AND '2018-09-24
    [3] => SELECT 'sell' as t_type, total_amount as total, fee_coinbase as fee, subtotal as amount, total_amount_currency as currency, 1 as ex_rate, created , id as trax_id, 'coinbase_transactions' as tb, status FROM coinbase_transactions WHERE wallet='EUR' AND userId='51' AND resource='buy' AND (DATE(created) BETWEEN '2018-08-24' AND '2018-09-24')

)
</pre>

2 个答案:

答案 0 :(得分:5)

您尝试过implode()吗?

$final_query = implode(' UNION ', array_filter($queries));

答案 1 :(得分:0)

如果这样做,您将在代码的最后一行之后有一个UNION,这样您就可以 sql1 UNION sql2 UNION sql3 UNION sql4 UNION。这将失败。

您可以执行以下操作:

function concatenate_queries($arr){
    $final_query = "";
    $union = "";
    foreach ($arr as $q){
        $final_query .= $union . $q;
        $union = ' UNION ';
    }
    return $final_query;
}

这样,您将拥有sql1 UNION sql2 UNION sql3 UNION sql4

编辑:Fabric的方法更有效,只需使用implode()。