mysql union of 2 tables - mysql

I have 2 tables:
table A (id, user_id, flag)
table B (id, user_id, flag)
Here If I take Count of table A it comes as 10 and that of B 5
So Total = 10 + 5 = 15.
SELECT * FROM table A
LEFT JOIN table B ON table B.user_id = table A.user_id
UNION ALL
SELECT * FROM table A
RIGHT JOIN table B ON table B.user_id = table A.user_id
So It should Come 15 instead it showing 50.

use
SELECT * FROM TABLE1 UNION
SELECT * FROM TABLE2
UNION removes duplicate records in other hand UNION ALL does not.Check HERE

You need to make sure the data in your tables are correct.
Table A Should have 15 rows
SELECT COUNT(*) as 'rowCountTableA' FROM table_a;
Table B Should have 5 rows
SELECT COUNT(*) as 'rowCountTableB' FROM table_b;
If your tables are correct and have exactly matching column names you can join them together by specifying asterisks to get all column values.
If however the columns in your table have a few different column names that are in table_a that are not in table_b you must call out the column names instead of using asterisk to get all values.
EXAMPLE:
SELECT (id,user_id,flag) FROM table_a
UNION ALL
SELECT (id,user_id,flag) FROM table_b

Related

How to filter out duplicates from a union query?

I have two similar SELECT queries that retrieve data from the same table "my_table".
-- 1st select
SELECT
my_table.id,
a,
b
FROM my_table
JOIN table2 ON u = v
JOIN table3 ON x = y
UNION ALL
-- 2st select
SELECT
my_table.id,
a,
b
FROM my_table
JOIN table2 ON r = s
JOIN table3 ON t = u
Duplicates are to be filtered out under the following conditions:
If the second select returns an id that is already present in the 1st select, it should be discarded.
Is there an easy solution without using a common table expression?
Note: The SQL does not have to be a UNION and can also be changed.
UNION filters out duplicate rows by default. UNION ALL does not remove duplicates.
But the duplicates are based on all columns being identical, not just the id column. If a given id value occurs in both queries, but any of the other two columns are different, then it counts as a distinct row.
If you want to reduce the result to a single row per id, the use a GROUP BY:
SELECT id, ...aggregate expressions...
FROM (
SELECT my_table.id, a, b ...
UNION
SELECT my_table.id, a, b ...
) AS t
GROUP BY id;
When you GROUP BY id, then any other expressions of the outer select-list must be in aggregate functions like MAX() or SUM(), etc.
The reason it is important to use an aggregate function is that when there are multiple rows with the same id value which you want to reduce to one row, what value should be displayed for a and b?
Example:
id
a
b
4
12
24
4
18
28
If you group by id, you would get one row for id=4, but what value for the other two columns?
id
a
b
4
?
?
Read https://dev.mysql.com/doc/refman/8.0/en/group-by-handling.html for more details on this. Or my answer to Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
You must use an aggregate function, which includes GROUP_CONCAT() to append all the values from that column in a comma-separated list. Or you can use ANY_VALUE() which picks one of the values from that column arbitrarily.
I think this should do it:
-- 1st select
SELECT
my_table.id,
a,
b
FROM my_table
JOIN table2 ON u = v
JOIN table3 ON x = y
WHERE id NOT IN (
SELECT
my_table.id,
FROM my_table
JOIN table2 ON r = s
JOIN table3 ON t = u
)
UNION ALL
-- 2st select
SELECT
my_table.id,
a,
b
FROM my_table
JOIN table2 ON r = s
JOIN table3 ON t = u

How to merge two tables on ID

I have two tables, who have the exact same columns. I want to merge table b into table a and if the dataset has the same ID, I want to use the dataset of table b.
I tried something like:
SELECT *
FROM
((SELECT
*
FROM
tableA) UNION (SELECT
*
FROM
tableB)) AS temp
GROUP BY temp.ID
ORDER BY temp.ID
but that gave me a mix of both tables.
You can do this using union all along with some additional logic:
select b.*
from b
union all
select a.*
from a
where not exists (select 1 from b where b.id = a.id);

pulling data from two different tables with common row elements

I have the following two tables:
Table a:
name qty
a 10
b 20
c 30
d 40
and table b
name qty
a 10
b 20
d 20
e 60.
I want to merge there two tables and create a new table like this
name qty
a 20
b 40
c 30
d 60
e 60
The objective is to add the values if there is have the same value in name or else just append the values in table two to table 1.
Unfortunately, MySQL does not support full outer join. Here is a method using union all and group by:
select name, sum(qty) as qty
from ((select name, qty from a) union all
(select name, qty from b)
) ab
group by name;
To simulate a full outer join, just execute a left outer join (gives all the rows of Table A with all matching rows of Table B or NULL) and a right outer join where Table A is NULL (gives all the rows of Table B that have no match in Table A -- matches are already provided in first query).
In the first query, there will always be a Qty value from Table A with either a Qty value or NULL from Table B. In the second query, there will only be a Qty value from Table B.
See Fiddle results.
select a.Name, a.Qty + IsNull( b.Qty, 0 ) as Qty
from #TableA a
left outer join #TableB b
on b.Name = a.Name
union all
select b.Name, b.Qty
from #TableA a
right outer join #TableB b
on b.Name = a.Name
where a.Name is null;
You may use union or union all with the same results. Since there is less processing required with union all, that's what I chose.

How to merge two tables keeping rows from first table

I have following two tables:
table1(a,b,c,d)
table2(a,b,c,d)
My requirement is to merge the two tables; if there are row(s) for combination of columns a and b (only combination of columns a and b, i.e, values for a and b are same) in both tables, keep the rows from first table.
I hope I am clear. Please suggest a query.
Note: Both tables don't have a primary key.
Thanks,
Update:
Left join on 's1.a = s2.a AND s1.b = s2.b' giving me duplicate rows and not picking the values from second table where column a and b values are not same. For example if I have 2 rows in table1 as:
11,22,33,44 --
11,55,33,44
and 2 rows in table2 as:
11,22,33,44 --
66,77,44,88
output is 4 rows as:
11,22,33,44 --
11,22,33,44 --
11,55,33,44 --
11,55,33,44
Update:
but output should be:
11,22,33,44 --
11,55,33,44 --
66,77,44,88
I thing I need UNION + JOIN + GROUP BY combination here but unable to come up with a right combination/query.
SELECT s1.* FROM
(SELECT a,b,c,d FROM table1) s1
LEFT JOIN
(SELECT a,b,c,d FROM table2) s2
ON s1.a = s2.a AND s1.b = s2.b
UPDATE:
SELECT a,b,c,d FROM table1 GROUP BY a,b,c,d
UNION
SELECT a,b,c,d FROM table2 GROUP BY a,b,c,d

mysql left join returns unexpected amount of rows

I have 2 tables where
tableA has 41 rows
and
tableB has 3 rows
I am trying to get the total rows of these 2 tables via a query using left join but i get way more rows(123) than expected(44)
query:
SELECT COUNT(*)
FROM tableA as u
LEFT JOIN tableB as d
ON u.uid=d.uid
WHERE
u.uid=912391178669
AND
u.deleted = 0
AND
d.deleted=0
tables schema:
tableA
id | uid | deleted
tableB
id | uid | deleted
I have run the following query It is working correctly.. U can check it out.
SELECT
( SELECT count(*) from table1 where.... )
+ ( SELECT count(*) from table2 where.... )
as total from dual
I'm guessing that you have three rows in tableA with the uid given in the query. That will mean that each row in tableA will join once with each row in tableB, which means you will back 41 x 3 rows or 123.
From the number of rows you are expecting back, I wonder if you need a Union instead of a join.
Select * from tableA where uid = 912391178669 and deleted = 0
union all
Select * from tableB where uid = 912391178669 and deleted = 0
A union will combine the results of two queries. A join will combine the columns of table tables in a single query.
41*3=123
each row of TableA has uid=912391178669 and tableB each row also have uid that's why you are getting 123 row total. use some filter criteria to get desired result (like some AND condition)
if you can show us your table column then it may be possible to help you .
Left join does not combine the rows of two table .
TableA left join TableB will give you all the row of table A meeting the joining condition.
SELECT COUNT(*)
FROM tableA as u
LEFT JOIN tableB as d
ON u.uid=d.uid
AND
u.deleted = d.deleted
WHERE
u.uid=912391178669
AND u.deleted = 0
SELECT SUM(
(SELECT count(*) from tableA WHERE uid=912391178669)
+ (SELECT count(*) from tableA WHERE uid=912391178669)
) as totalRows