简体   繁体   中英

if no results returned from first query then use second query

I am making a system in which i need to check if a email exist in first table or second table.

    $results = mysqli_query($db,"SELECT * FROM table_1 WHERE email='$email'");
    if(count($results) == 0)
    {
        $results = mysqli_query($db,"SELECT * FROM table_2 WHERE email='$email'");
    }

I wanted to make one mysql so that there is no need for two. Since both table structures are different UNION is not not giving proper results. Is there a way without UNION or JOINS

I have been trying it with UNION

SELECT * FROM ( SELECT *, 1 as preference FROM table_1 WHERE email = 'doc@demo.com' UNION SELECT *, 2 as preference FROM table_2 WHERE email = 'doc@demo.com' ) T ORDER BY preference LIMIT 1

But the problem is if table 2 case satisfy then table 1 fields are considered and all values gets mismatched

I found a solution to my own question so just wanted to share it

SELECT * FROM (
  SELECT email,password,user_role, id as customer_id,id as user_id, 1 as preference 
    FROM table1 WHERE email = 'raj@demo.com'
   UNION 
  SELECT email,password,user_role, customer_id,id, 2 as preference 
    FROM table2 WHERE email = 'doc@demo.com' 
) T ORDER BY preference
LIMIT 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM