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

    $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的方法吗

我一直在尝试与UNION

SELECT * FROM ( SELECT *, 1 as preference FROM table_1 WHERE email = '[email protected]' UNION SELECT *, 2 as preference FROM table_2 WHERE email = '[email protected]' ) T ORDER BY preference LIMIT 1


但是问题是如果表2的大小写满足,则考虑表1的字段并且所有值都不匹配

最佳答案

我找到了自己问题的解决方案,所以只想分享一下

SELECT * FROM (
  SELECT email,password,user_role, id as customer_id,id as user_id, 1 as preference
    FROM table1 WHERE email = '[email protected]'
   UNION
  SELECT email,password,user_role, customer_id,id, 2 as preference
    FROM table2 WHERE email = '[email protected]'
) T ORDER BY preference
LIMIT 1

关于php - 如果第一个查询没有返回结果,则使用第二个查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51274290/

10-16 12:56