2012-11-26 96 views
2

我有两个要连接在一起的查询,但我不知道该如何操作。将多列查询转换为行

Select father, mother, guardian from students where user_id = '201209291';

我得到3个ID的结果。

现在,我需要使用这三个ID来获取他们的个人信息;

Select * from system_users where user_id = (The 3 IDs from the previous query);

我将如何去解决这个问题呢?我把第一个查询的结果想成3行,但我不知道该怎么做。

回答

2

好了,你只要能直接加入连接谓词使用一系列OR S,作为fathermother,并guardian列实际上是user_id S IN system_users。

select usrs.* 
from students s 
join system_users usrs on 
    s.father=usrs.user_id OR 
    s.mother=usrs.user_id OR 
    s.guardian=usrs.user_id 
where s.user_id = '201209291'; 
+0

是的,想要添加这种可能性也给我的答案... +1从我:) – fancyPants

+0

唯一的其他选择是使用数据透视表,这是完全矫枉过正的需要什么。这可能是最简单的方法(尽管我希望你可以在现代数据库管理系统中使用'IN(s.father,s.mother,s.guardian)'这样的东西。) – SPFiredrake

+0

Accepted!Thank you very much =) – Cartman

0

为什么不使用连接?

Select father, mother, guardian from students as s 
join system_users usrs 
on s.user_id=usrs.user_id 
where s.user_id = '201209291'; 
3
Select * from system_users where user_id IN 
(
Select father from students where user_id = '201209291' 
UNION 
Select mother from students where user_id = '201209291' 
UNION 
Select guardian from students where user_id = '201209291' 
) 
+0

非常好!但我喜欢加入的想法更多=) – Cartman

0

从第一个查询中,您将不会有ID,而是3列。

Select father, mother, guardian from students where user_id = '201209291'

也许你的意思是

Select distinct some_id from students where user_id = '201209291'

我建议很简单:

Select * from system_users where user_id in (Select distinct some_id from students where user_id = '201209291');

  • 我有没有正确的理解这个问题?