0

我有一个如下所述的 mysql 查询,它准确地返回我想要的一行结果,但不返回任何其他我希望在我的测试数据中有 8 个的行(有 8 个唯一的测试 ID)。我受到这个答案的启发,但显然搞砸了我的实现,有人知道我哪里出错了吗?

SELECT 
c.first_name,
c.last_name,
n.test_name,
e.doc_name,
e.email,
e.lab_id,
a.test_id,
a.date_req,
a.date_approved,
a.accepts_terms,
a.res_value,
a.reason,
a.test_type,
a.date_collected,
a.date_received,
k.kind_name,
sum(case when metabolite_name = "Creatinine" then t.res_val end) as Creatinine,
sum(case when metabolite_name = "Glucose" then t.res_val end) as Glucose,
sum(case when metabolite_name = "pH" then t.res_val end) as pH
   FROM test_requisitions      AS a
   INNER JOIN personal_info    AS c   ON (a.user_id = c.user_id)
   INNER JOIN test_types       AS d   ON (a.test_type = d.test_type)
   INNER JOIN kinds            AS k   ON (k.id = d.kind_id)
   INNER JOIN test_names       AS n   ON (d.name_id = n.id)
   INNER JOIN docs             AS e   ON (a.doc_id = e.id)
   INNER JOIN test_metabolites AS t   ON (t.test_id = a.test_id)
   RIGHT JOIN metabolites      AS m   ON (m.id = t.metabolite_id)
   GROUP BY a.test_id
   ORDER BY (a.date_approved IS NOT NULL),(a.res_value IS NOT NULL), a.date_req, c.last_name ASC;
4

1 回答 1

1

您的大多数联接都是inner joins。最后一个是right outer join. 如所写,查询保留所有的metabolites,但不一定是所有的测试。

我建议您将它们全部更改为left outer joins,因为您想保留第一个表中的所有行:

   FROM test_requisitions      AS a
   LEFT JOIN personal_info    AS c   ON (a.user_id = c.user_id)
   LEFT JOIN test_types       AS d   ON (a.test_type = d.test_type)
   LEFT JOIN kinds            AS k   ON (k.id = d.kind_id)
   LEFT JOIN test_names       AS n   ON (d.name_id = n.id)
   LEFT JOIN docs             AS e   ON (a.doc_id = e.id)
   LEFT JOIN test_metabolites AS t   ON (t.test_id = a.test_id)
   LEFT JOIN metabolites      AS m   ON (m.id = t.metabolite_id)

我还建议您的别名与表相关,例如trfor test_requisitionpiforpersonal_info等。

于 2013-05-01T18:32:42.327 回答