A 表
userId Name
1 张三
2 李四B表
Id userId scores
1 1 80
2 1 70
3 2 70
4 2 60说明A表和B表通过 userId关联
现在我想通过A表关联B表查询不出现笛卡积(用left join 或 inner join 实现不了)
想得到的结果:(因为考虑到想查姓名,所以必须联合),但又不能用distinct
userId Name scores
1 张三 80
2 李四 60指教感谢!!

解决方案 »

  1.   


    select a.userid,max(b.scores)
    from a inner join b on a.userid=b.userid
    group by a.userid
    说实话,根本就没看懂你需要什么。 你的结果中scores是什么机制来的?为什么两条70的都没了?提问也是一种学问.
        [align=center]====  ====
    [/align]
    .
    贴子分数<20:对自已的问题不予重视。
    贴子大量未结:对别人的回答不予尊重。
    .
      

  2.   

    其实我要的重点不是在于scroes,我要实现的是两表联合查询如果一条记录对应多条记录,肯定查出来是笛卡尔积!但我现在想查出来 的是如果一条记录对应多条记录,我想查出来该条记录对应多条记录里面的第一条(永远通过id升序的第一条)A 表 
    userId Name 
    1 张三 
    2 李四 B表 
    Id userId scores 
    1 1 80 
    2 1 70 
    3 1 75
    4 1 77
    .
    .
    .
    . 2 70 
    n 2 60                       
    即查出来(永远只有两条记录)
    userId Name scores 
    1     张三    80(这个值是id倒排取的第一个值) 
    2     李四    70 (同上)
      

  3.   

    这个值是id倒排取的第一个值]如ID相同时取最大?
      

  4.   

    mysql> create table a_table
        -> (userId int,
        -> Name varchar(20)
        -> );
    Query OK, 0 rows affected (0.52 sec)mysql> create table b_table
        -> (id int,
        -> userId int,
        -> scores float);
    Query OK, 0 rows affected (0.52 sec)mysql> insert into a_table values (1,'张三');
    Query OK, 1 row affected (0.39 sec)mysql> insert into a_table values (2,'李四');
    Query OK, 1 row affected (0.09 sec)mysql> insert into b_table
        -> select 1,1,80 union all
        -> select 2,1,70 union all
        -> select 3,2,70 union all
        -> select 4,2,60;
    Query OK, 4 rows affected (0.06 sec)
    Records: 4  Duplicates: 0  Warnings: 0mysql> select a.*,b.* from a_table a left join b_table b on a.userId=b.userId gr
    oup by a.userId;
    +--------+------+------+--------+--------+
    | userId | Name | id   | userId | scores |
    +--------+------+------+--------+--------+
    |      1 | 张三 |    1 |      1 |     80 |
    |      2 | 李四 |    3 |      2 |     70 |
    +--------+------+------+--------+--------+
    2 rows in set (0.00 sec)
    是否符合LZ要求?
      

  5.   


    select userId, Name, scores from 
    (select a.userId, a.Name, b.scores from A left join B on a.userId = b.userId 
    order by a.userId asc, b.scores asc) x group by userId