如果第一个查询没有返回结果,那么使用第二个查询

gr8qqesn  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(339)

我正在制作一个系统,我需要检查电子邮件是否存在于第一个表或第二个表中。

$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'");
    }

我想做一个mysql,这样就不需要两个了。因为这两种表结构是不同的 UNION 没有给出正确的结果。有没有一条没有 UNION or JOINS 我一直在和工会一起尝试

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

但问题是如果表2的case满足,那么表1的字段就会被考虑,所有的值都会不匹配

ubby3x7f

ubby3x7f1#

我找到了解决我自己问题的方法,所以我想和大家分享一下

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

相关问题