mysql& PDO - 排序和过滤结果的行数

时间:2015-08-12 05:05:34

标签: php mysql sql-server

我使用PDO和PHP处理mysql数据库。我有一个不同建筑物中的工会成员列表,我试图让它进行数据库查询以获得成员的资历数。

数据库设置如下:

memberID
memberName
memberBuildingNumber
memberHireDate (2000-05-01 as an example)
memberPIN (Used in case of ties between hire date, lower pin is higher seniority)

我知道SQL以正确的顺序对成员进行排序:

SELECT * FROM  `members` ORDER BY  `members`.`memberHireDate` ASC, `members`.`memberPIN` ASC WHERE building = buildingB

(是的,我知道我的陈述是错误的)

我不知道如何计算行数来获得会员的位置。

例如:

1457 John Smith BuildingB 2000-05-01 4745
1875 Jane Smith BuildingB 2000-05-01 4010
1407 Johnny Good BuildingB 2010-08-01 4745

所以在我上面运行第二个查询之后或者我必须要做的事情,如果我正在寻找Jane的资历号码,我会以1回来。

1 个答案:

答案 0 :(得分:0)

我实际做的是在DB中的成员表中添加另一列。它包含资历编号,由脚本设置。如果任何人对未来感兴趣,这是脚本。

$dbh = new PDO('mysql:host=localhost;dbname=DBNAME', $db_user, $db_password);
$stmt = $dbh->prepare('SELECT memberBuildingNumber FROM BuildingCodes WHERE BuildingCode > 0');
$stmt->execute();

foreach ($stmt->fetchAll() as $results) {
    $memberBuildingNumber = $results['memberBuildingNumber'];

$dbh = new PDO('mysql:host=localhost;dbname=DBNAME', $db_user, $db_password);
$stmt = $dbh->prepare('SELECT * FROM members WHERE memberBuildingNumber=? ORDER BY memberHireDate ASC, memberPIN ASC');
$stmt->execute(array($memberBuildingNumber));

$seniority = 1;
$memberSeniorityLastUpdate = date("Y-m-d H:i:s");

foreach ($stmt->fetchAll() as $results) {

    $dbh = new PDO('mysql:host=localhost;dbname=DBNAME', $db_user, $db_password);
    $stmt = $dbh->prepare('UPDATE members SET memberSeniority=?, memberSeniorityLastUpdate=? WHERE memberID=?');
    $stmt->execute(array($seniority, $memberSeniorityLastUpdate, $results['memberID']));

    $seniority++;
   }
}