Alternative to UNION clause in Mysql - mysql

I have two table :- table a, table b.
table a
---ID---
1
2
3
4
5
7
table b
---ID----
2
3
4
5
6
I have to get Output Like this without UNION Command:-
----ID-----
1
2
3
4
5
6
7
Note: I have one solution with union:-
**select * from a
UNION
select * from b;**
I need alternative to this. please experts suggest.

We need another table with (at least) 2 rows for this:
CREATE TABLE d
( id INT NOT NULL
);
INSERT INTO d
(id)
VALUES
(0), (1) ;
Then, if we want to have only one query, we can use (this is for fun, DO NOT USE in production, that's why we have UNION):
SELECT DISTINCT
COALESCE(aa.id, bb.id) AS id
FROM
d
LEFT JOIN a AS aa ON d.id = 0
LEFT JOIN b AS bb ON d.id = 1
WHERE
COALESCE(aa.id, bb.id) IS NOT NULL
ORDER BY
id ;
Tested at SQLfiddle.com, and for other table combinations:
1 row - 1 row
2 rows - 2 rows
0 rows - 1 row
0 rows - 2 rows
0 rows - 0 rows

try this:
I think it works well in MS-SQL, change it to MySQL if you need, but MYSql doesnot support full outer join! Good luck
SELECT (
CASE
WHEN b.ID IS NULL
THEN a.ID
WHEN b.ID=a.ID
THEN b.ID
ELSE b.ID
END)
FROM
(SELECT ID FROM table2
)b
FULL OUTER JOIN
(SELECT ID FROM table1
) a
ON a.ID=b.ID
and play around with the query
Fiddle: http://sqlfiddle.com/#!3/c657d/13
And here is the MYSQL version:
SELECT DISTINCT COALESCE(t1.id, t2.id) id
FROM
(
SELECT TABLE_NAME <> 'table_a' n
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = SCHEMA()
AND TABLE_NAME IN('table_a', 'table_b')
) t LEFT JOIN table_a t1
ON t.n = 0 LEFT JOIN table_b t2
ON t.n = 1
Working fiddle: http://sqlfiddle.com/#!2/c657d8/34

I don't know why you are avoiding UNION but you can do like following
CREATE TABLE temp_ids(ID INT);
INSERT INTO temp_ids SELECT ID FROM a;
INSERT INTO temp_ids SELECT ID FROM b;
SELECT DISTINCT ID FROM temp_ids;

Try a full outer join and filter the NULL values.

As an abstract exercise (if this is an interview question we expect a kickback!) one ugly, innefficient solution would be to create a cartesian product and filter the unique values:
SELECT DISTINCT IF(a<>b, b.id, a.id)
FROM a, b
ORDER BY 1
;

Use FULL OUTER JOIN, like this:
SELECT CASE
WHEN t1.id IS NULL THEN t2.id
ELSE t1.id
END AS id
FROM t1
FULL OUTER JOIN t2
ON t1.id = t2.id
ORDER BY id
Note: Mysql does not support full outer joins.
Working demo: http://sqlfiddle.com/#!6/b7684/10

Related

SQL to fetch data where Unique key matches but the data is different in some other columns between different tables

I have two tables of same structure as below. I am trying to write a query to compare both the tables using the Unique key which is the first column and trying to return values when there is a mismatch in the second column.
If the key is not present then no need to consider that data. only if the key is present in both the table then we have compare it.
Table A
ColumnA ColumnB
A 1
B 2
C 2
D 8
Table B
ColumnC ColumnD
A 1
B 3
C 5
F 4
For example the output of the above table when comparing Table A with B should be
B 2
C 2
and when comparing Table B with A it should be
B 3
C 5
Ideally the difference in the base table should come.
I have tried Joins and Unions but I am not able to fetch the data as mentioned above.
Since you want only those rows which has matching FK values in both the tables, we simply need to use INNER JOIN.
Now, we can simply consider the unmatching rows by using WHERE .. <> ..
When comparing Table A against Table B, we can get Table A rows only:
SELECT
tA.*
FROM tableA AS tA
JOIN tableB AS tB
ON tB.ColumnC = tA.ColumnA
WHERE tB.ColumnD <> tA.ColumnB
When comparing Table B against Table A, simply fetch the rows from Table B only:
SELECT
tB.*
FROM tableA AS tA
JOIN tableB AS tB
ON tB.ColumnC = tA.ColumnA
WHERE tB.ColumnD <> tA.ColumnB
I would do :
SELECT t.*
FROM tablea t
WHERE EXISTS (SELECT 1 FROM tableb t1 WHERE t1.cola = t.cola AND t1.colb <> t.cold);
Same would be for second version just need to swipe the table names.
use EXISTS and union all
SELECT t.*
FROM tablea t
WHERE EXISTS (SELECT 1 FROM tableb t1 WHERE t1.cola = t.cola AND t1.colb <> t.colb)
union all
SELECT t.*
FROM tableb t
WHERE EXISTS (SELECT 1 FROM tablea t1 WHERE t1.cola = t.cola AND t1.colb <> t.colb)

need help on join query condtion

I am not much in db queries and I require some help on following .
I have two table structures as follow as
table1 :
Name Id1 Id2
Jack 1 1
Jack 1 1
Jack 1 1
table2 :
Name Id1 Id2
Jack 1 1
I used basic join query :
select *
from table1 tb1
join table2 tb2 on tb1.id1 = tb2.id1
and tb2.id2 = tb2.id2
output I get :
Jack 1 1
Jack 1 1
Jack 1 1
But I required following output:
Jack 1 1
Note: I like to show what records is available in table 2 when it combined together!!.. I would like to fetch data with respect table2 only
Thanks in advance.
Please try the following (does not uses aliases) ...
SELECT table2.Name,
table2.Id1,
table2.Id2
FROM table1
JOIN table2 ON table1.id1 = table2.id1 AND
table1.id2 = table2.id2
GROUP BY table2.id1,
table2.id2;
Or try the following (does use aliases)...
SELECT tb2.Name,
tb2.Id1,
tb2.Id2
FROM table1 tb1
JOIN table2 tb2 ON tb1.id1 = tb2.id1 AND
tb1.id2 = tb2.id2
GROUP BY tb2.id1,
tb2.id2;
By performing an INNER JOIN on table2 with table1 on those key fields you are limiting the output to only those rows from table1 that match Id1 and Id2 in table2 (Note : Where JOIN is not preceded by a JOIN type an INNER JOIN is performed). Since multiple rows in table1 meet this criteria you can limit your results to just one row for each matching set of criteria using GROUP BY
This should change the supplied actual query to...
SELECT delta.input_name,
delta.mtcn,
delta.at‌​tempt_id
FROM compliance.rtra_transactions rtra_txn
JOIN compliance.GNR_TEST_RUNS delta ON rtra_txn.mtcn_nr = delta.mtcn
AND rtra_txn.attemptid = delta.attempt_id
WHERE rtra_txn.year = 2017
AND rtra_txn.month = 2
AND rtra_txn.day = 17
AND rtra_txn.trns_ts BETWEEN '2017-02-17 00:00:00' AND '2017-02-17 23:59:00'
AND delta.MATCH_OUTCOME = 'MATCH'
AND delta.job_name = 'Feb17_Run_1'
AND rtra_txn.txn_map[ 'TRANSACTIONTYPE' ] IN ( '10', '7' )
GROUP BY delta.mtcn,
delta.attempt_id;
If you have any questions or comments, then please feel free to post a Comment accordingly.
Following query should work :
SELECT * FROM TBL2 T2
UNION
SELECT * FROM TBL1 T1;
You need to use LEFT JOIN as you mentioned in Biswabid answer comment I like to show what records is available in table 2 alone
select DISTINCT tb2.*
from table2 tb2
left join table1 tb1 on tb1.id1 = tb2.id1
and tb1.id2 = tb2.id2
WHERE tb1.id1 IS NULL

How to merge(columns) outputs of two SELECT statements in oracle sql?

I have two Select queries.
The first Select query gives the output which has two columns viz.
A B
------
1 2
3 4
5 6
7 8
The second Select query given the output which as two columns viz Column B and Column C. All the values in Column B of this select statement matches the values of Column B of the first Select statement.i.e
B C
------
2 25
4 50
6 30
8 50
Now, I need to merge the outputs of the above two Select queries. i.e
A B C
----------
1 2 25
3 4 50
5 6 30
7 8 50
I cannot use views to store the output of the two select queries. I need to use the Column B in both select queries to merge. However, I am not able to figure out how to go about it.
If you have elaborated queries (not just tables to join), you may try using with construction
with
Query1 as ( -- <- Put your 1st Query text here
select A,
B
...
),
Query2 as ( -- <- Put your 2nd Query text here
select B,
C
...
)
select Query1.A,
Query1.B,
Query2.C
from Query1,
Query2
where Query1.B = Query2.B
If your case is not that complicated, e.g. both Query1 and Query2 are in fact tables, say Table1 and Table2 you can do well with a simpler solution:
select Table1.A,
Table1.B,
Table2.C
from Table1,
Table2
where Table1.B = table2.B
Consider you tables like having fields like
TableA(A ,B) , TableB(B,C)
Try using JOIN like
SELECT TableA.A , TableA.B, TableB.C
FROM TableA
JOIN TableB ON TableA.B = TableB.B;
This can be accomplished by joining your first table to your second table using an INNER JOIN on the B column:
SELECT T1.A,
T1.B,
T2.C
FROM Table1 T1
INNER JOIN Table2 T2 ON T2.B = T1.B
Note that I called your first table Table1 (alias T1) and your second table Table2 (alias T2) as I was unsure of their names.
SELECT one.a, one.b, two.c
FROM table1 one JOIN table2 two
ON one.b = two.b
You can use Join
SELECT A.A,
A.B,
B.C
FROM Table1 A
INNER JOIN Table2 B ON B.B = A.B

Selecting two rows in a table which have the same data for a particular column

There is a column in a table(contracts) called service location. I have to show all the rows where the service locations matches any other row in the table.
Table Example
A B C
1 2 3
3 2 1
2 5 3
I require a query where the first and second rows will be returned based on a comparison on the second column. I am assuming I will need to use a HAVING COUNT(B) > 1
I came up with this
SELECT `contract_number`
FROM `contracts`
WHERE `import_id` = 'fe508764-54a9-41f7-b36e-50ebfd95971b'
GROUP BY `service_location_id`
HAVING COUNT(`service_location_id` ) >1
But it doesn't generate what I exactly need.
Having would do it, but you would need to use it like this
SELECT *
FROM Contracts
INNER JOIN
( SELECT B
FROM Contracts
GROUP BY B
HAVING COUNT(*) > 1 -- MORE THAN ONE ROW WITH THE SAME VALUE
) dupe
ON dupe.B = Contracts.B
Depending in your indexing you may find a self join performs better though:
SELECT DISTINCT t1.*
FROM contracts t1
INNER JOIN contract` t2
ON t1.B = t2.B
AND t1.A <> t2.A
SELECT *
FROM sheet1
WHERE C
IN (
SELECT C
FROM sheet1
GROUP BY C
HAVING COUNT( C ) >1
)
ORDER BY C
LIMIT 0 , 5000

Select distinct records in mysql

My table
ANONYMOUS
ONE TWO
1 2
2 1
1 2
3 1
Now i want to select distinct set of one and two.
My selected list should be
ANONYMOUS
ONE TWO
1 2
3 1
Your question isn't very clear, but I guess you mean this:
SELECT DISTINCT one, two
FROM yourtable AS T1
WHERE one <= two
OR NOT EXISTS
(
SELECT *
FROM yourtable AS T2
WHERE T1.one = T2.two
AND T1.two = T2.one
)
It finds rows with (one, two) where the reversed pair (two, one) does not exist. If both exist, it chooses the pair such that one < two. It also selects rows where the values are equal.
See it working online: sqlfiddle
If you would prefer to use a JOIN instead of NOT EXISTS you can do that:
SELECT DISTINCT T1.one, T1.two
FROM yourtable AS T1
LEFT JOIN yourtable AS T2
ON T1.one = T2.two
AND T1.two = T2.one
WHERE T1.one <= T1.two
OR T2.one IS NULL
See it working online: sqlfiddle
SELECT DISTINCT a.*
FROM `ANONYMOUS` a
LEFT JOIN `ANONYMOUS` b ON (a.one=b.two and a.two=b.one)
WHERE b.one is null or a.one<b.one
ORDER BY 1,2