如何从多个表中选择记录
表“用户”: user_id |用户名|电子邮件|登录|密码
表“ users_log” log_id | user_id |状态|时间戳|消息
表“ users_balance” balance_id | user_id |状态|金额
表“ users_roles” role_id |状态|角色名称
表“ users_role” role_id | user_id
如何通过用户电子邮件以及日志状态和用户角色来检索所有记录
输出: 日志时间戳| user_id |用户名|电子邮件|角色名称|余额|日志消息
答案 0 :(得分:1)
您可以使用 JOIN 查询从多个表中获取数据
请尝试一下
SELECT usr.*,usrlg.*,usrbl.*,usrrl.*,usrrls.* FROM users AS usr JOIN users_log AS usrlg ON(usrlg.user_id=usr.user_id) JOIN users_balance AS usrbl ON (usrbl.user_id=usr.user_id)
JOIN users_role AS usrrl ON(usrrl.user_id=usr.user_id) JOIN users_roles AS usrrls ON(usrrls.role_id=usrrl.role_id)
WHERE usr.email='value' AND usrlg.status='value' AND usrrls.role_name='value'
答案 1 :(得分:1)
我猜是这样的。
SELECT
log.timestamp AS log_timestamp,
u.user_id,
u.username AS user_name,
u.email AS user_email,
role.name AS role_name,
bal.amount AS balance_amount,
log.message AS log_message
FROM users AS u
JOIN users_role AS ur ON ur.user_id = u.user_id
JOIN users_roles AS role ON role.role_id = ur.role_id
JOIN users_log AS log ON u.user_id = log.user_id
LEFT JOIN users_balance AS bal ON bal.user_id = u.user_id
WHERE u.email = @UserEmail
AND role.role_name = @RoleName
AND log.status = @LogStatus
然后用您要查找的内容设置或替换@ UserEmail,@ RoleName,@ LogStatus变量。
但是根据数据,您可能想要添加GROUP BY和aggregate function,例如MAX或SUM,并可能在WHERE或HAVING子句中添加其他条件。
答案 2 :(得分:0)