在查询中使用多个IF

时间:2015-10-25 09:27:56

标签: mysql subquery

我有以下查询,我按预期得到结果:

    SELECT
      IF (a1>b1,'1','0') AS a1r,
      IF (a2>b2,'1','0') AS a2r,
      IF (a3>b3,'1','0') AS a3r,
      IF (a4>b4,'1','0') AS a4r,
      IF (a5>b5,'1','0') AS a5r,
      IF (a6>b6,'1','0') AS a6r,
      IF (a7>b7,'1','0') AS a7r,
      SUM(a1r+a2r+a3r+a4r+a5r+a6r+a7r) AS ar
      FROM fab_matches
      WHERE p1 = 12 AND p2 = 15;

但是我想生成一个查询(可能带有子查询),只得到' ar'而不是其他人。 我知道这很容易,但我被困住了! 提前致谢

4 个答案:

答案 0 :(得分:1)

你没有 在子查询中执行它,虽然这是最常用的方法,但这也有效:

SELECT
    IF (a1>b1,'1','0')
  + IF (a2>b2,'1','0')
  + IF (a3>b3,'1','0')
  + IF (a4>b4,'1','0')
  + IF (a5>b5,'1','0')
  + IF (a6>b6,'1','0')
  + IF (a7>b7,'1','0')  AS ar
FROM fab_matches
WHERE p1 = 12 AND p2 = 15;

每个IF表达式只是简单地计算为单个值,因此您可以直接在算术中使用它们。

答案 1 :(得分:0)

您必须在子查询中执行此操作:

SELECT a1r, a2r, a3r, a4r, a5r, a6r, a7r,
a1r+a2r+a3r+a4r+a5r+a6r+a7r AS ar
FROM (
  SELECT
  IF (a1>b1,'1','0') AS a1r,
  IF (a2>b2,'1','0') AS a2r,
  IF (a3>b3,'1','0') AS a3r,
  IF (a4>b4,'1','0') AS a4r,
  IF (a5>b5,'1','0') AS a5r,
  IF (a6>b6,'1','0') AS a6r,
  IF (a7>b7,'1','0') AS a7r /*you have to change the alias here, since you already used it in the first line*/
  FROM fab_matches
  WHERE p1 = 12 AND p2 = 15
) subquery_alias;

您不能在同一SELECT子句中引用别名。

处理查询的顺序是

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. ORDER BY
  6. 选择

答案 2 :(得分:0)

你可以这样做

select 
  SUM(a1r+a2r+a3r+a4r+a5r+a6r+a7r) AS ar
  from (
   SELECT
   IF (a1>b1,'1','0') AS a1r,
   IF (a2>b2,'1','0') AS a2r,
   IF (a3>b3,'1','0') AS a3r,
   IF (a4>b4,'1','0') AS a4r,
   IF (a5>b5,'1','0') AS a5r,
   IF (a6>b6,'1','0') AS a6r,
   IF (a7>b7,'1','0') AS a1r
   FROM fab_matches
   WHERE p1 = 12 AND p2 = 15
 )x ;

答案 3 :(得分:0)

请你试试这个简单的方法 -

SELECT 
SUM(IF(a1>b1,'1','0')+IF(a2>b2,'1','0')+IF(a3>b3,'1','0')+IF(a4>b4,'1','0')+IF(a5>b5,'1','0')+IF(a6>b6,'1','0')+IF(a7>b7,'1','0')) AS ar
FROM fab_matches
WHERE p1 = 12 AND p2 = 15;