Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Same table union from different databases

I have 03 MySQL databases as 2022_db, 2023_db and 2024_db. All the tables and table structures in the 03 databases are same & included different values.I want to get the sum of values in two tables in 02 databases 2022_db and 2023_db into a single report. Tables are named as vote & finacne_budget_issue. The columns are as vote and amount. I used the following query to do that.

 public function amt_tot()
{
    $otherdb2022 = $this->load->database('2022_db', TRUE);
    $otherdb2023 = $this->load->database('2023_db', TRUE);
    $q = $this->db->query("
     select 
            SELECT finance_vote.vote, SUM(amount) AS amount
            FROM (
            SELECT finance_vote.vote, SUM(amount) AS amount AS amt_2022
            FROM $otherdb2022.finance_budget_issue
            GROUP BY vote
            UNION ALL
            SELECT finance_vote.vote, SUM(amount) AS amount AS amt_2023
            FROM $otherdb2023.finance_budget_issue
            GROUP BY vote
    ) AS tot
    GROUP BY vote");

    if ($q->num_rows() > 0) {
        $results = $q->result();
        return $results;
    }
}

But the query says that systax error "near ‘SELECT vote, SUM(amount) AS amount FROM….. ". What may be going wrong in my query ? Can any one help this for me ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have double aliased the sums, e.g.

SUM(amount) AS amount AS amt_2022

However, a better pattern to use here would be to union the two tables first, then aggregate that as a subquery and take the totals:

SELECT vote, SUM(amount) AS amount
FROM (
    SELECT vote, amount
    FROM table_2022
    UNION ALL
    SELECT vote, amount
    FROM table_2023
) t
GROUP BY vote;

By the way, it is generally bad practice to bind a table name using a PHP variable. This opens your code to outside SQL injection attacks. That being said, if you are certain that $otherdb2022 and $otherdb2023 would not be getting populated from outside data, then it might be safe.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading