mysql pivot查询结果中缺少行

时间:2013-05-01 18:28:03

标签: mysql pivot

我有一个如下所述的mysql查询,它会返回我想要的一行结果,但不返回任何其他行,我希望在我的测试数据中有8个(有8个独特的测试ID) 。我受到了this answer的启发,但显然搞砸了我的实施,有人看到我哪里出错吗?

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;

1 个答案:

答案 0 :(得分:1)

你的大部分联接都是inner join。最后一个是right outer join。如上所述,查询保留所有metabolites,但不一定是所有测试。

我建议您将它们全部更改为left outer join,因为您希望将所有行保留在第一个表中:

   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)

我还建议你的别名与表格相关,trtest_requisitionpipersonal_info,依此类推。