使用UNION在多个表中进行选择

时间:2011-05-20 00:08:28

标签: mysql select union

我将数据库从一个用户表重新编写为多个用户表(按角色划分):tblStudentstblTeacherstblAdmin

登录时,我不想运行三个查询来检查用户是否存在于我的数据库中的某个位置。所以我所做的是将以下查询与union

放在一起
select s.id as id, s.email as email, s.password as password, s.role as role from tblStudents s
union
select a.id as id, a.email as email, a.password as password, a.role as role from tblAdmin a
union
select t.id as id, t.email as email, t.password as password, t.role as role from tblTeachers t

这会选择所有表格中相同的字段,并为我输出结果。

所以,我决定试试这个,出于某种原因,我的登录表单不起作用。对于我的登录表单,我添加了一个where子句来检查电子邮件地址。我在我的数据库应用程序中运行了查询,令人惊讶的是,当我执行where email = "admin@admin.be"时(此电子邮件存在于我的数据库tblAdmin中),它还会从我的学生表中选择一条记录。

使用where子句:

select s.id as id, s.email as email, s.password as password, s.role as role from tblStudents s
union
select a.id as id, a.email as email, a.password as password, a.role as role from tblAdmin a
union
select t.id as id, t.email as email, t.password as password, t.role as role from tblTeachers t
where email = "admin@admin.be"

记录have id = 1但我不明白为什么在我过滤管理员电子邮件地址时会选择学生记录。为什么是这样?有人可以解释并为我提供更好的解决方案吗?我基本上有一个登录表单,需要在多个表中选择以检查用户是否存在于我的数据库中。

2 个答案:

答案 0 :(得分:11)

感谢您更新查询;现在我们可以看到WHERE条件仅应用于 last UNIONed查询。您需要 将WHERE子句添加到每个查询中,或将其包装为子选择并将WHERE子句应用于该子查询。

select s.id as id, s.email as email, s.password as password, s.role as role from tblStudents s
where email = "admin@admin.be"
union
select a.id as id, a.email as email, a.password as password, a.role as role from tblAdmin a
where email = "admin@admin.be"
union
select t.id as id, t.email as email, t.password as password, t.role as role from tblTeachers t
where email = "admin@admin.be"

SELECT * FROM (
select s.id as id, s.email as email, s.password as password, s.role as role from tblStudents s
union
select a.id as id, a.email as email, a.password as password, a.role as role from tblAdmin a
union
select t.id as id, t.email as email, t.password as password, t.role as role from tblTeachers t
) foo where email = "admin@admin.be"

答案 1 :(得分:0)

SELECT
    R.co_C,
    company3.Statuss
FROM
    (
        SELECT
            company1.co_C
        FROM
            company1
        UNION ALL
            SELECT
                company2.co_C
            FROM
                company2
    ) AS R
LEFT JOIN company3 ON R.co_C = company3.co_A;