解决方案 »

  1.   

       建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
       参考一下这个贴子的提问方式http://bbs.csdn.net/topics/320211382
       
       1. 你的 create table xxx .. 语句
       2. 你的 insert into xxx ... 语句
       3. 结果是什么样,(并给以简单的算法描述)
       4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
       
       这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。
      

  2.   


    感谢解答。
    问题:create table A
    (
    a_id   varchar(10),
    name varchar(20),
    b_ID  varchar(20)
    )
    insert into AA select '1','a1','1'
    insert into AA select '1','a1','2'
    insert into AA select '2','a2','3'create table B
    (
    b_id   varchar(10),
    status varchar(20)
    )
    insert into test2 select '1','1'
    insert into test2 select '2','2'
    insert into test2 select '3','1'A表 通过b_id与 B表关联
    情景:A表里存在两条a_id都是1的记录,分别对应了两条B表的记录,分别status=1和status=2。select * from A left join B on A.b_id=B.b_id  where ..........
    /*
    要得到这样的报表:
    1,A表关联B表,查询所有的A表记录,要求a_id唯一.
    2,如果同一个a_id关联的B表记录有两条,取status为1的。如果关联的B表记录只有一条,就取那一条,不管status=1还是2*/
      

  3.   


    查询结果a.id唯一。
    如果存在两条,取关联的B.status=1的一条,如果只有一条就取这一条,不管B.status=1还是B.status=2。
      

  4.   


    a_id     name     b_id     status 
       1           a1          1             1
    create table A
    (
    a_id   varchar(10),
    name varchar(20),
    b_ID  varchar(20)
    )insert into AA select '1','a1','2'
    insert into AA select '2','a2','3'
     
    create table B
    (
    b_id   varchar(10),
    status varchar(20)
    )insert into test2 select '2','2'
    insert into test2 select '3','1'如果数据是这样,结果就是a_id     name     b_id     status 
       1           a1          2             2
      

  5.   

    mysql> select * from a;
    +------+------+------+
    | a_id | name | b_ID |
    +------+------+------+
    | 1    | a1   | 2    |
    | 2    | a2   | 3    |
    +------+------+------+
    2 rows in set (0.00 sec)mysql> select * from b;
    +------+--------+
    | b_id | status |
    +------+--------+
    | 2    | 2      |
    | 3    | 1      |
    +------+--------+
    2 rows in set (0.00 sec)mysql> select * from A left join B on A.b_id=B.b_id ;
    +------+------+------+------+--------+
    | a_id | name | b_ID | b_id | status |
    +------+------+------+------+--------+
    | 1    | a1   | 2    | 2    | 2      |
    | 2    | a2   | 3    | 3    | 1      |
    +------+------+------+------+--------+
    2 rows in set (0.00 sec)mysql>
    楼主最好解释一下为什么第二条记录不取? 另外建议楼主在提供测试用数据时能自己先测试一遍。 
    mysql> select * from A left join B on A.b_id=B.b_id limit 1;
    +------+------+------+------+--------+
    | a_id | name | b_ID | b_id | status |
    +------+------+------+------+--------+
    | 1    | a1   | 2    | 2    | 2      |
    +------+------+------+------+--------+
    1 row in set (0.00 sec)mysql>
      

  6.   


    不好意思,我的意思是:
    1.如果存在两条,取关联的B.status=1的一条
    2.如果只有一条就取这一条,不管B.status=1还是B.status=2。这个答案貌似不能满足1吧?