2012-06-25 36 views
1

如果我有这样的使用结果在不同的表

table_1 

Field 1: victories 
Field 2: name 

table_2 

Field 1: name 
Field 2: birthday 

三个不同的表现在,我想要得到的人的生日最胜利。

所以我会做这样的事情(伪代码):

select victories from table_1 and sum_it_all 
get name and pass name to table_2 
select birthday from table_2 where name 

好吧,这是很丑陋的伪代码,但我希望你明白了吧。

使用Andomar的解决方案工作正常。 现在我试图巢另一个表中它,这样虽然:

select address 
from table_3 
where birthday = 
    (
    select birthday 
    from table_2 
    where name = 
      (
      select name 
      from table_1 
      group by 
       name 
      order by 
       sum(victories) desc 
      limit 1 
      ) 
    ) 

我得到一个正确的答案,但因为某些原因也得到了null回来。我将如何输出胜利的总和?

+0

你的问题是这个? 这看起来像你有你的问题的答案.. –

回答

1
select birthday 
from table_2 t2 
where name = 
     (
     select name 
     from table_1 t1 
     order by 
       victories desc 
     limit 1 
     ) 

如果一个用户可以在table_1有多行,你必须sum胜利:

select birthday 
from table_2 t2 
where name = 
     (
     select name 
     from table_1 t1 
     group by 
       name 
     order by 
       sum(victories) desc 
     limit 1 
     ) 
+1

胜利总结在哪里? –

+0

这个答案假设'table_1'和'table_2'之间的关系是1:1。我将为1:多关系添加一个版本 – Andomar

+0

谢谢。它适用于两个表格。你能再看看我的初始帖子吗? –

1

我想你要寻找的是这样的:

SELECT t2.name, SUM(t1.victories) as SumOfVictories, t2.birthday 
FROM table_1 as t1 
JOIN table_2 as t2 
ON table_1.name = table_2.name 
GROUP BY t2.name, t2.birthday 
ORDER BY SUM(t1.victories) DESC 
LIMIT 1 
+0

很好的答案。从我+1。我正在删除我对OP请求的明显误解。 – swasheck

0

SELECT * FROM table_1 INNER JOIN table_2 ON table_1.name=table_2.name ORDER BY victories DESC会给你想要的结果吗?

-1

试试这个:

Select name, birthday from table_2 t2 
     Join table_1 t1 On t1.Name = t2.name 
    Having Count(*) = 
     (Select Max(namCount) 
      From (Select Count(*) namCount 
       From table_1 
       Group By name)) 
    Group By t1.name 
+2

我不认为你可以像max(count(*))'嵌套聚合? – Andomar

+0

正确,当我将概念从大脑转录到网站时,我省略了第二个子查询! –

1

您可以使用下面嵌套的SQL:

select name, birthday from table_2 where name in (
    select name from table_1 order by victories desc limit 1 
    ) 
0

这可能是你的问题的解决方案:

SELECT table_1.name, table_2.birthday 
FROM table_2 
JOIN table_1 ON table_1.name=table_2.name 
WHERE table_1.victories>=ALL(SELECT table_1.victories 
          FROM table_1)