Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to UNION clause in 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.

like image 917
Shrikant Gupta Avatar asked Jan 17 '26 23:01

Shrikant Gupta


1 Answers

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

like image 166
ypercubeᵀᴹ Avatar answered Jan 20 '26 15:01

ypercubeᵀᴹ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!