SQL从同一个表中选择列

时间:2012-08-31 16:29:31

标签: mysql sql

我将直接用我的表格潜入,很快就会明白我的问题

表1:

Owner    ownerID    Name    Address    userID
______________________________________________
Name        1       Tim    "top road"    1   

表2:

User      userID    userName    password    secretQA1    secretQA2
___________________________________________________________________
            1        BigTim       pwhat         7           8

表3:

secretQA  id    question       answer
_______________________________________
          7     "Mums name"     "Tony"
          8     "Fav sport"     "dressing up"

无论如何我想做的是我知道ownerID是1,我想给主人他所有的信息!所以我一直在做的是这样的事情:

SELECT secretQA.question AS Question1, secretQA.answer AS Answer1,
secretQA.question AS Question2, secretQA.answer AS Answer2,
User.password AS Password
FROM secretQA, owner, User
WHERE owner.id = 1
AND SecretQA.id = owner.secretQA1
AND SecretQA.id = owner.secretQA2
AND user.id = owner.userID; 

但无济于事!

这是我想要获得的:

Question1    Answer1    Question2    Answer2        Password
____________________________________________________________
"Mums name"   "Tony"    "Fav sport"  "dressing up"  pwhat  

为将来的所有帮助干杯

编辑:密码只是这里的一个例子,在我的真实版本中不是纯文本这只是我正在做的事情的简化问题

3 个答案:

答案 0 :(得分:1)

要获得您想要的东西,您必须两次加入SecretQA表。这是为什么使用显式连接语法更好的一个例子。

这应该有效

     SELECT q1.question AS Question1, 
            q1.answer AS Answer1,
            q2.question AS Question2,
            q2.answer AS Answer2,
            u.password AS Password
       FROM User u
       JOIN owner o ON u.id = o.userID
  LEFT JOIN secretQA q1 on o.secretQA1 = q1.id
  LEFT JOIN secretQA q2 on o.secretQA2 = q2.id
      WHERE owner.id = 1

请注意,您的secretQA表必须参加两次加入。我已经给它了别名q1q2来完成这项工作。

哦,就像其他人说的那样,如果你把密码存储为纯文本,请告诉他。 intertubz会pou u,srsly。

答案 1 :(得分:0)

在表2中,删除'secret1'和'secret2'列。在表3中,添加一个新列'userID'。

之后,您应该可以执行类似

的操作
select u.username, u.password, s.question, s.answer
from table1 as o join table2 as u on o.userid = u.userid
join table3 as s on s.userid = o.userid
where o.ownerid = 1

另外,正如其他人所说,将密码存储为纯文本并不是一个好主意。

答案 2 :(得分:0)

试试这个

 SELECT q1.question, q1.answer, q2.question, q2.answer, u.password
   FROM user u
   JOIN secretqa q1 ON u.secretQA1 = q1.id
   JOIN secretqa q2 ON u.secretQA2 = q2.id
  WHERE u.id = ?