Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php/mysql Merge 2 tables with same Columns correctly

Tags:

php

mysql

EDIT: Thanks For JoseCarlosPB here is the solution:

SELECT
  (select count(DISTINCT userscount) AS duplicates from users1)
  +
  (select count(DISTINCT userscount) AS duplicates from users2) AS duplicates
FROM dual;

So i have 2 tables and a mysql statement i want to merge 2 tables but there is same column in both.I think There is nothing to do in PHP code i think the problem is in the mysql statement.

my code works(no errors) but it gives unexpected output.i simply want to correctly count userscount here is what i mean: table1 has 32 users and table2 has 44 users i thought the output will be 76 users but it is 3244

PHP:

include 'conn00.php';
    $sql = "select DISTINCT userscount, count(DISTINCT userscount) AS duplicates from users1 UNION ALL
     select DISTINCT userscount, count(DISTINCT userscount) AS duplicates from users2";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo $row["duplicates"];
        }
    } else {

    }

table1:

users1 

32

table2:

users2 

44    

output: 3244 i want the output to be 76

If the solution is in mysql will be better bcz i have more similar sql statements and i want apply the solution for all of it. thanks for answering

like image 245
easy pz Avatar asked Dec 13 '22 09:12

easy pz


1 Answers

I think you can do it this way, almost like alistaircol said

SELECT
  (select count(DISTINCT userscount) AS duplicates from users1)
  +
  (select count(DISTINCT userscount) AS duplicates from users2) AS duplicates
FROM dual;
like image 77
JoseCarlosPB Avatar answered Dec 18 '22 00:12

JoseCarlosPB