我正在尝试从数据库中获取一些数据。
用户名
来自登录表email
来自联系人表
检查两个表 tutor
和 institute
中的 2 个值
到目前为止,这是我的代码:
SELECT s. * , c.email, l.username
FROM (
SELECT contact_id AS id,
login_id,
username,
tutor_code AS code,
tutor_name AS Name,
'tutor' AS profile
FROM tutors
WHERE tutor_code = $code AND tutor_name = '$name'
UNION ALL
SELECT contact_id AS id,
login_id,
username,
institute_code AS code,
institute_name AS Name,
'institute' AS profile
FROM institutes
WHERE institute_code = $code AND institute_name = '$name'
)
INNER JOIN contact c ON s.id = c.contact_id
INNER JOIN login l ON s.login_id = l.login_id
此查询无效,并且有一条错误消息。
1054 - Unknown column 'username' in 'field list'
更新
SELECT s. * , c.email, l.username
FROM (
SELECT contact_id AS id,
login_id,
username,
tutor_code AS code,
tutor_name AS Name,
'tutor' AS profile
FROM tutors
WHERE tutor_code = $code AND tutor_name = '$name'
UNION ALL
SELECT contact_id AS id,
login_id,
username,
institute_code AS code,
institute_name AS Name,
'institute' AS profile
FROM institutes
WHERE institute_code = $code AND institute_name = '$name'
)s
INNER JOIN contact c ON s.id = c.contact_id
INNER JOIN login l ON s.login_id = l.login_id
最佳答案
由于您正在从 login
中检索您的 username
,username
列很可能不存在于 tutors
和/或 institutes
,加入 login
也不是必需的,因为您是通过 login_id
加入的,我想您可以只需从子查询中删除 username
列:
SELECT s. * , c.email, l.username
FROM (
SELECT contact_id AS id,
login_id,
--username,
tutor_code AS code,
tutor_name AS Name,
'tutor' AS profile
FROM tutors
WHERE tutor_code = $code AND tutor_name = '$name'
UNION ALL
SELECT contact_id AS id,
login_id,
--username,
institute_code AS code,
institute_name AS Name,
'institute' AS profile
FROM institutes
WHERE institute_code = $code AND institute_name = '$name'
) s
INNER JOIN contact c ON s.id = c.contact_id
INNER JOIN login l ON s.login_id = l.login_id
我还向您的 subuqery 添加了别名 s
,因为我认为它的遗漏是一个打字错误,因为如果没有它会引发语法错误
关于mysql - 从3个表中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16358770/