如何在mysql中检索具有特定条件的记录?

时间:2016-04-07 01:39:13

标签: mysql

SQL声明:

SELECT 
    b.*,
    e.Lastname,
    e.Firstname,
    e.ID_SC,
    e.Program,
    r.BReasonDetails
FROM
    tblbadgetemporaryborrower b
        INNER JOIN
    (SELECT 
        e.*, p.Program
    FROM
        tblemployee e
    INNER JOIN tblemployeeprogram p ON p.ID_P = e.ID_P) e ON e.EmployeeID = b.EmployeeID
        INNER JOIN
    tblbadgetemporaryborrowerreason r ON r.ID_BR = b.ID_BR
HAVING e.ID_SC = {$_GET['ID_SC']}
ORDER BY b.EmployeeID ASC

问:如何仅使用Lost原因检索员工数据并计算其发生次数。

screenshot

预期输出:

100827038 | Larrazabal, Victor Ceasar | 4 (`Lost` count)

2 个答案:

答案 0 :(得分:1)

您需要做的就是在查询中添加WHERE子句

SELECT
      b.*,
      e.Lastname,
      e.Firstname,
      e.ID_SC,
      e.Program,
      r.BReasonDetails
      FROM tblbadgetemporaryborrower b
        INNER JOIN (
                     SELECT e.*, p.Program 
                     FROM tblemployee e 
                       INNER JOIN tblemployeeprogram p ON p.ID_P = e.ID_P
                   ) e ON e.EmployeeID = b.EmployeeID
      INNER JOIN tblbadgetemporaryborrowerreason r ON r.ID_BR = b.ID_BR

      WHERE r.BReasonDetails = 'Lost'

      HAVING e.ID_SC = {$_GET['ID_SC']} 
      ORDER BY b.EmployeeID ASC

答案 1 :(得分:1)

首先,在现有查询中,您可以使用where而不是having。此外,您不希望FROM子句中的子查询。然后你可以用另一个条件来补充这个:

SELECT b.*, e.Lastname, e.Firstname, e.ID_SC, p.Program, r.BReasonDetails
FROM tblbadgetemporaryborrower b INNER JOIN
     tblemployee e
     e.EmployeeID = b.EmployeeID JOIN
     tblemployeeprogram p
     ON p.ID_P = e.ID_P INNER JOIN
     tblbadgetemporaryborrowerreason r
     ON r.ID_BR = b.ID_BR
WHERE e.ID_SC = {$_GET['ID_SC']} AND
      EXISTS (SELECT 1
              FROM tblbadgetemporaryborrowerreason r2
              WHERE r2.ID_BR = b.ID_BR AND r2.BReasonDetails = 'Lost'
             )
ORDER BY b.EmployeeID ASC;

编辑:

我以为你想要的所有行都是Lost。但我发现你确实想要一个聚合查询:

SELECT b.*, e.Lastname, e.Firstname, COUNT(*) as LostCount
FROM tblbadgetemporaryborrower b INNER JOIN
     tblemployee e
     e.EmployeeID = b.EmployeeID JOIN
     tblemployeeprogram p
     ON p.ID_P = e.ID_P INNER JOIN
     tblbadgetemporaryborrowerreason r
     ON r.ID_BR = b.ID_BR
WHERE e.ID_SC = {$_GET['ID_SC']} AND r.BReasonDetails = 'Lost'
GROUP BY b.EmployeeId