没有得到表的列

时间:2016-12-29 15:29:20

标签: mysql

CREATE TABLE login(
  name varchar(200),
  email varchar(200) primary key, 
  count int,
  depart varchar(200),
  type varchar(1),
  password varchar(40));

CREATE TABLE qsstudent(
 department varchar(200),
 qs int,
 email varchar(200),
 type varchar(1),
 qscorrect int,
 qsdone int,
 qswrong int ,
 FOREIGN KEY (email) REFERENCES login(email));

CREATE TABLE qsteacher(
  email varchar(200),
  department varchar(200),
  qsentered int,
  type varchar(1),
  FOREIGN KEY (email) REFERENCES login(email));

当我运行下面的查询时,找不到login.depart列。我已经尝试过几次,但它没有运行。我认为外键中没有错误

   SELECT qsteacher.qsentered 
   FROM login,qsteacher 
   WHERE login.depart=qsteacher.department 
   AND qsstudent.email=login.email;

但仍然存在错误。

2 个答案:

答案 0 :(得分:1)

  

找不到login.depart列

这是您的查询无法找到的确切内容:

SELECT qsteacher.qsentered 
FROM login,qsteacher
WHERE login.depart=qsteacher.department 
AND qsstudent.email=login.email; //<-- you didn't select qsstudent

如果您想在此查询中使用qsstudent,则需要将其添加到FROM

FROM login,qsteacher,qsstudent

我建议使用INNER JOIN执行类似的操作:

SELECT T3.qsentered 
FROM login as T1
INNER JOIN qsstudent as T2 on T2.email=T1.email
INNER JOIN qsteacher as T3 on T1.depart=T3.department

如果您想要按特定用户选择,只需将此WHERE添加到结尾:

WHERE T1.email = 'user_email'

答案 1 :(得分:0)

首先,您的主键应该是id,而不是电子邮件,原因有多种,例如唯一性和索引。所以我将为你的所有表添加一个id,它应该随每个记录自动递增。你的外键也应该是一个id,所以我会改变它。

CREATE TABLE login(
  id int NOT NULL AUTO_INCREMENT primary key,
  name varchar(200),
  email varchar(200), 
  count int,
  depart varchar(200),
  type varchar(1),
  password varchar(40));

CREATE TABLE qsstudent(
 id int NOT NULL AUTO_INCREMENT primary key,
 department varchar(200),
 qs int,
 email varchar(200),
 type varchar(1),
 qscorrect int,
 qsdone int,
 qswrong int ,
 FOREIGN KEY (login_id) REFERENCES login(id));

CREATE TABLE qsteacher(
  id int NOT NULL AUTO_INCREMENT primary key,
  email varchar(200),
  department varchar(200),
  qsentered int,
  type varchar(1),
  FOREIGN KEY (login_id) REFERENCES login(id));

现在针对您尝试从我能说的内容中运行的查询:

SELECT q.qsentered FROM qsteacher q
JOIN login l ON l.id = q.login_id
JOIN qsstudent s ON s.login_id = l.id
WHERE s.department = q.department

请准确评论您要查询的内容,以便我可以更好地回答您的问题。目前尚不清楚你在寻找什么。