skip to Main Content

I have two tables

tbl1:
id
userid
subscriptionid
column2
column3

tbl2:
id
userid
subscriptionid
column4
column5
Column6
Column7

The subscriptionid values are unique, and would only exist in tbl1 or tbl2, but may also be null

I need a query to find a subscriptionid in either tbl1 or tbl2

SELECT * FROM tbl1, tbl2 WHERE (tbl1.subscriptionid OR tbl2.subscriptionid) = 'some_val';

2

Answers


  1. You can achieve this by using the SQL UNION operator to combine the results from both tables and then filter for the specific value you’re looking for. Here’s how you can write the query:

    SELECT subscriptionid FROM tbl1 WHERE subscriptionid = 'some_val'
    UNION
    SELECT subscriptionid FROM tbl2 WHERE subscriptionid = 'some_val';
    

    This query will return a result set that includes the subscriptionid values from either tbl1 or tbl2 where the subscriptionid matches the specified value ‘some_val’. The UNION operator ensures that duplicate values are removed from the result set, and you’ll get a unique list of matching subscriptionid values from both tables.

    I hope this solves your problem..

    Login or Signup to reply.
  2. Just normalize the SELECT list between the two queries in the UNION ALL:

    SELECT id, userid, subscriptionid, column2, column3, NULL AS column4, NULL AS column5, NULL AS column6, NULL AS column7
    FROM tbl1 WHERE subscriptionid = ?
    UNION ALL
    SELECT id, userid, subscriptionid, NULL AS column2, NULL AS column3, column4, column5, column6, column7
    FROM tbl2 WHERE subscriptionid = ?
    

    Here’s a db<>fiddle.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search