MySql返回Distinctive记录

时间:2013-05-18 12:55:48

标签: mysql sql

我已经编写了以下sql语句,在测试表上,我有4条记录,在coa_body表上我也有4条记录,这个查询:

SELECT `name`, `compedia`, `specification`
  FROM    (`tests` t, `coa_body` cb)
  JOIN
      `request_details` rd
    ON `t`.`id` = `rd`.`test_id`
 WHERE `rd`.`request_id` = 'NDQA201303001' AND cb.labref = 'NDQA201303001';

返回:

1.name compedia规范

Assay                     Alphy     poxy
pH(Acidity/Alkalinity)    Alphy     poxy
Sterility                 Alphy     poxy
Bacterial Endotoxin Test  Alphy     poxy
Assay                     poxy      alphy
pH(Acidity/Alkalinity)    poxy      alphy
Sterility                 poxy      alphy
Bacterial Endotoxin Test  poxy      alphy
Assay                     alphy1    poxy1
pH(Acidity/Alkalinity)    alphy1    poxy1
Sterility                 alphy1    poxy1
Bacterial Endotoxin Test  alphy1    poxy1
Assay                     poxy1     alphy1
pH(Acidity/Alkalinity)    poxy1     alphy1
Sterility                 poxy1     alphy1
Bacterial Endotoxin Test  poxy1     alphy1

2.coa_body表如下:     id labref compedia规范

1   NDQA201303001   Alphy   poxy
2   NDQA201303001   poxy    alphy
3   NDQA201303001   alphy1  poxy1
4   NDQA201303001   poxy1   alphy1

3.我只需要4个与coa_body表完全相同的记录,如下所示

   name                     compedia   specification

   Assay                     Alphy  poxy
   pH(Acidity/Alkalinity)    poxy   alphy
   Sterility                 alphy1 poxy1
   Bacterial Endotoxin Test  poxy1  alphy1

4.如果我添加GROUP BY t.name语句,则在查询结束时返回

 name                   compedia  specification     

Assay                       Alphy   poxy
Bacterial Endotoxin Test    Alphy   poxy
pH(Acidity/Alkalinity)      Alphy   poxy
Sterility                   Alphy   poxy

这不是我想要的,我想要的结果是3号的那个

1 个答案:

答案 0 :(得分:-1)

重写您的查询

SELECT `name`, `compedia`, `specification`
  FROM    (`tests` t, `coa_body` cb)
  JOIN
      `request_details` rd
    ON `t`.`id` = `rd`.`test_id`
 WHERE `rd`.`request_id` = 'NDQA201303001' AND cb.labref = 'NDQA201303001' GROUP BY name;