3 つのテーブル (顧客、蜂の巣、検査) を持つデータベースがあります。各検査には、蜂の巣と顧客が 1 つずつしかありません。1 人の顧客が多くの養蜂箱を持つことができ、1 つの養蜂箱が多くの検査を受けることができます)。
理想的には、私がやりたいことは、各顧客の各巣箱の最新の検査を見て、死んでいる巣箱の数と生きている巣箱の数を数えることです (検査テーブルの「蜂の巣強度」フィールドの値に基づいて.
これはしばらくの間私を混乱させてきました.私のコードは恐ろしく、おそらくそれを行うための最良の方法ではないからだと思います.
誰かが次の表を達成するのを手伝ってくれるかどうか知りたいです:
顧客名 | 最新の検査 | 総ライブじんましん | 死んだ蕁麻疹の総数
これが私の半作業コードです(注意してください-すべての罪として醜いです):
$ContactsQ = mysql_query("
SELECT
*
FROM
Contacts
WHERE
`Contacts`.`Status` = 'Active'
AND
`Contacts`.`Type` = 'Rental'
GROUP BY
ContactID
");
if (!$ContactsQ) {
die('Invalid query: ' . mysql_error());
}
echo "<table class=\"tablesorter\" >";
echo "<thead><tr>";
echo "<th>ID     </th>";
echo "<th> Name</font></th>";
echo "<th>Live Hives</font></th>";
echo "<th>Dead Hives</font></th>";
echo "<th>Last Inspected</font></th>";
echo "<th>AG</font></th>";
echo "</tr></thead>";
// For Each Customer//
while(($CQ = mysql_fetch_assoc($ContactsQ))) {
$live = 0;
$dead = 0;
$CID = $CQ['ContactID'];
$Query = mysql_query("
SELECT
MAX(`InspectionsNZ`.`InsID`) Ins,
Hives.* ,
Contacts.*
FROM
`InspectionsNZ`
LEFT JOIN `Contacts` ON `Contacts`.`ContactID` = `InspectionsNZ`.`CustomerID`
LEFT JOIN `Hives` ON `Hives`.`ID` = `InspectionsNZ`.`HiveID`
WHERE
`Hives`.`Status` = 'Active'
AND Contacts.ContactID = $CID
GROUP BY
`ID`
");
if (!$Query) {
die('Invalid query: ' . mysql_error());
}
// For Each Hive the customer has that is active
while(($row1 = mysql_fetch_assoc($Query))) {
$HID = $row1['ID'];
$lastinsID = $row1['Ins'];
$Query1 = mysql_query("
SELECT
HiveStrength, Date, InsID, CustomerID
FROM
InspectionsNZ
WHERE
`InsID` = $lastinsID
ORDER BY
`InsID`
");
if (!$Query1) {
die('Invalid query: ' . mysql_error());
}
// Add to total if Alive or Dead
while(($row = mysql_fetch_assoc($Query1))) {
//Get current CustomerID//
$nquery = mysql_query("
SELECT
MAX(`InspectionsNZ`.`InsID`) ,
`CustomerID`
from
`InspectionsNZ`
WHERE
`HiveID` = $HID
");
if (!$nquery) {
die('Invalid query: ' . mysql_error());
}
while(($nrow = mysql_fetch_assoc($nquery))) {
$NCID = $nrow['CustomerID'];
}
//END Get current CustomerID//
if ($CID == $NCID){
if($row['HiveStrength'] > 0) {
$live++;
}
elseif($row['HiveStrength'] == 0) {
$dead++;
}
}
echo $HID." - ".$NCID." - ".$row['CustomerID']." - ".$CID." - ".$lastinsID." - ".$row['Date']."<br/>";
}
}
echo "<tr>";
echo "<td><h3>" .$CQ['ContactID']. "</h3></td>";
echo "<td><a href='CustomerTop.php?cid=" .$CQ['ContactID']. "'>" .$CQ['Name']. "</a></td>";
echo "<td><h3>" .$live. "</h3></td>";
echo "<td><h3>" .$dead. "</h3></td>";
echo "<td><h3>" .$CQ['Date']. "</h3></td>";
echo "<td><h3>" .$CQ['RunGroup']. "</h3></td>";
}
echo "</tr>";
echo "</tbody>";
echo "</table><br />";
私が得ているのは顧客のリストですが、生きているじんましんと死んでいるじんましんの計算が正しくありません...
助けてください :)
ジュリアン