首页 > 解决方案 > 从两个表中的任何一个中获取单行

问题描述

我有一个供管理员和用户使用的登录页面。他们都使用相同的表单,并且包含电子邮件和密码字段。

admins除了调用 admins 表和调用 users之外,数据库表是相同的users。电子邮件字段对两者都是唯一的,例如,如果电子邮件“test@example.com”在users表格中,则它不会在admins表格中。

从两个表中获取行、返回该行并检查它从哪个表中获取的最佳方法是什么?

联合、连接、2 个SELECT查询,或者其他可以执行得更快、更高效的东西?

SELECT * FROM admins
UNION
SELECT * FROM users
WHERE email = :email

或者可能有两个选择:

$row = SELECT * FROM admins WHERE email = :email LIMIT 1
if(!$row) {
    $row = SELECT * FROM users WHERE email = :email LIMIT 1
}

// Then I want to do redirect them according to what type of user they are:
if(row comes from admins table) {
    header('Location: /admins');
} else {
    header('Location: /users');
}

也许有其他方式?

标签: phpmysqljoinselectunion

解决方案


首先,您应该有一个用户信息表,并添加一个角色表来区分管理员和普通用户。但如果你不能这样做,有一个解决方案。

 SELECT a.* , 'admin' as role FROM admins a
 UNION
 SELECT u.* , 'user' as role FROM users u
 WHERE email = 'abc@email.com'

“角色”列将告诉您从哪个表中获取值。


推荐阅读