在不同的表中使用SQL查询的结果

时间:2012-06-25 18:45:33

标签: mysql sql

如果我有三个不同的表

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。我将如何输出胜利总和?

6 个答案:

答案 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 :(得分: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

答案 2 :(得分:1)

您可以使用以下嵌套SQL:

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

答案 3 :(得分:0)

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

答案 4 :(得分: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)

答案 5 :(得分:-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