mysql - 按间隔查询和/或不返回任何内容

时间:2015-06-25 07:15:41

标签: php mysql

我只需要选择来自用户表的电子邮件,其中weekly_mail(日期时间)早于一周或为空,如果用户的积分加起来超过10。现在没有退货。

points_plus表结构

id | user_id | points | date
1    62        5        2015-05-13 08:42:37
2    62        15       2015-05-14 03:12:32

查询

$q = "SELECT u.email, u.weekly_mail, SUM(p.points) AS points
      FROM users u
      LEFT JOIN points_plus p
      ON u.id = p.user_id
      WHERE points > 10 AND u.weekly_mail < NOW() - INTERVAL 1 WEEK OR u.weekly_mail = NULL
      GROUP BY p.user_id";
$result = $this->db->mysqli->query($q);

if (!$result) {
    printf("Query failed: %s\n", $this->db->mysqli->error);
    exit;
}

$rows = array();
while($row = $result->fetch_row()) {
    $rows[]=$row;
}

$result->close();
return $rows;

2 个答案:

答案 0 :(得分:1)

  SELECT u.email, u.weekly_mail, SUM(p.points) AS points
  FROM users u
  LEFT JOIN points_plus p
   ON u.id = p.user_id
  WHERE u.weekly_mail < NOW() - INTERVAL 1 WEEK OR u.weekly_mail = NULL
  GROUP BY p.user_id having SUM(p.points) > 10

答案 1 :(得分:0)

检查一下:

$q = "SELECT u.email, u.weekly_mail, SUM(p.points) AS points
      FROM users u
      LEFT JOIN points_plus p
      ON u.id = p.user_id
      WHERE u.weekly_mail < (NOW() - INTERVAL 1 WEEK) OR u.weekly_mail IS NULL
      GROUP BY p.user_id having SUM(p.points) > 10";