php - 从两个表中的任何一个中获取单行
问题描述
我有一个供管理员和用户使用的登录页面。他们都使用相同的表单,并且包含电子邮件和密码字段。
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');
}
也许有其他方式?
解决方案
首先,您应该有一个用户信息表,并添加一个角色表来区分管理员和普通用户。但如果你不能这样做,有一个解决方案。
SELECT a.* , 'admin' as role FROM admins a
UNION
SELECT u.* , 'user' as role FROM users u
WHERE email = 'abc@email.com'
“角色”列将告诉您从哪个表中获取值。
推荐阅读
- testing - TestCafe - 错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
- deno - 如何从 deno.land 开始?
- r - 给定数据框中的一系列用户和他们观看的电影,我如何对用户观看的所有电影进行分组?
- sql - Postgresql:用逗号分割字符串并合并
- r - 如何在 R 中创建这个变量?
- r - R - 来自简单数据框的 Wordcloud
- r - 如何在 R 中的 write.csv() 中为文件名附加后缀?
- r - dplyr `is_grouped_df()` 实际上是否需要日期框架(与数据表、tibble 等相比)?
- docker - 无法在 docker 中构建 .net 核心 API 映像
- api - date_start 和 date_stop 默认 api fb