过滤和限制查询

时间:2014-02-17 17:44:39

标签: php mysql sql

我想在我的查询中寻求帮助......我想要做的是,如果表格中的具体aticoaic为空...... interview_sum或{ {1}}对于特定的other_sum atic也应该是空的....有谁知道怎么做?

当前输出的图片:enter image description here

当前查询:我的查询仍然为other_sum或interview_sum提供数字,甚至是空的。

oaic

1 个答案:

答案 0 :(得分:1)

我做了一些假设:

  • 您可能有一个表,app_interview2.atic和other_app2.oaic是外键,但由于您没有共享它,我在FROM子句中派生了一个表。
  • 这假定atid的atname始终相同。
  • 你也除以7 - 我假设是得到平均值,所以我使用了AVG功能。

解---

SELECT t1.id AS atid
       ,interview.atname AS atname
       ,COALESCE(interview.interviewsum, 0) AS interviewsum
       ,COALESCE(interview.interviewavg,0) AS interviewavg 
       ,COALESCE(other.othersum, 0) AS othersum
       ,COALESCE(other.otheravg) AS otheravg
FROM (SELECT DISTINCT atid AS id
      FROM app_interview2
      UNION
      SELECT DISTINCT oaic 
      FROM other_app2) AS t1
LEFT JOIN (SELECT atid, atname, SUM(inttotal) AS interviewsum, AVG(inttotal) AS interviewavg
           FROM app_interview2
           GROUP BY atid, atname) as interview
  ON interview.atid = t1.id
LEFT JOIN (SELECT oaic, SUM(ototal) AS othersum, AVG(ototal) AS otheravg
           FROM other_app2
           GROUP BY oaic) AS other
  ON other.oaic = t1.id;

- 如果这给出了您希望得到的结果,我会将FROM子句中的 t1 派生表替换为我上面描述的主键并且可能具有这些列的表(例如,region) ,小镇等)我没有包括