何时使用Where子句和ON子句加入mysql查询?

时间:2017-09-26 09:42:36

标签: php mysql

我有以下sql JOIN查询:

public function exportAll($date) {
    $sql = "SELECT CONCAT(u.firstname, u.lastname) as fullname, c.early_checkout_remarks, c.delayed_checkin_remarks, DATE(c.checkin_time) as checkin_date, DATE(c.checkout_time) as checkout_date, TIME(c.checkin_time) as checkin_time, TIME(c.checkout_time) as checkout_time 
    FROM users u
    LEFT JOIN checkin_checkout c 
    ON u.id=c.users_id 
    AND (DATE(c.checkin_time) = '%s' OR DATE(c.checkout_time) = '%s') 
    AND u.deleted IS NULL
    ORDER BY fullname,checkin_date";
    $records = $this->db->exec(sprintf($sql,$date,$date));
    return $records;

我只想要未删除用户的记录。但是此查询还会返回“已删除”列中包含值的用户。

3 个答案:

答案 0 :(得分:1)

尝试以下查询。

SELECT CONCAT(u.firstname, u.lastname) as fullname, c.early_checkout_remarks, c.delayed_checkin_remarks, DATE(c.checkin_time) as checkin_date, DATE(c.checkout_time) as checkout_date, TIME(c.checkin_time) as checkin_time, TIME(c.checkout_time) as checkout_time 
    FROM users u
    LEFT JOIN checkin_checkout c 
    ON u.id=c.users_id 
    Where (DATE(c.checkin_time) = '%s' OR DATE(c.checkout_time) = '%s') 
    AND u.deleted IS NULL
    ORDER BY fullname,checkin_date

答案 1 :(得分:1)

$sql = "SELECT CONCAT(u.firstname, u.lastname) as fullname, c.early_checkout_remarks, c.delayed_checkin_remarks, DATE(c.checkin_time) as checkin_date, DATE(c.checkout_time) as checkout_date, TIME(c.checkin_time) as checkin_time, TIME(c.checkout_time) as checkout_time 
FROM users u
LEFT JOIN checkin_checkout c ON u.id=c.users_id 
WHERE (DATE(c.checkin_time) = '%s' OR DATE(c.checkout_time) = '%s') 
AND u.deleted IS NULL
ORDER BY fullname,checkin_date";
$records = $this->db->exec(sprintf($sql,$date,$date));
return $records;

在JOIN之后添加了WHERE。您也可以使用ON。

答案 2 :(得分:1)

为此,我认为你需要搬家

AND u.deleted IS NULL 

进入WHERE子句。目前,AND仅应用于连接,而不是最终结果。由于它是LEFT加入,因此不会完全限制结果。

尝试:

SELECT 
  CONCAT(u.firstname, u.lastname) as fullname, 
  c.early_checkout_remarks, 
  c.delayed_checkin_remarks, 
  DATE(c.checkin_time) as checkin_date, 
  DATE(c.checkout_time) as checkout_date, 
  TIME(c.checkin_time) as checkin_time, 
  TIME(c.checkout_time) as checkout_time 
FROM 
  users u
  LEFT JOIN 
    checkin_checkout c 
      ON u.id = c.users_id 
      AND (DATE(c.checkin_time) = '%s' OR DATE(c.checkout_time) = '%s') 
WHERE 
  u.deleted IS NULL
ORDER BY 
  fullname,
  checkin_date

从您的问题中不清楚关于登记日期的部分也应该在where子句中。我们需要了解有关需求和数据结构的更多信息。但是如果你需要,你可以试试。

另请注意,我重新格式化了您的查询 - 我(个人)发现这样格式化的查询可以更快,更准确地读取和理解。可以更容易地看到在哪里做什么,以及什么适用于什么。