考虑下面的数据库设置,以获得更多信息:的一种方式围绕具有遍历结果使用第一个结果集
Customers
| customerId | accountId | addressId |
|------------|-----------|-----------|
| 1 | 110 | 8 |
| 2 | 120 | 9 |
| 3 | 130 | 10 |
Address
| addressId | companyName | state |
|-----------|-------------|-------|
| 8 | FooBar Co | FL |
| 9 | Self Co | VA |
| 10 | Cli Co | CA |
Tests
| testId | accountId | testType | Status |
|--------|-----------|----------|---------|
| 1 | 120 | Urine | Done |
| 2 | 110 | Blood | Pending |
| 3 | 110 | Blood | Pending |
| 4 | 130 | Biopsy | Done |
| 5 | 130 | Blood | Done |
| 6 | 130 | Urine | Pending |
| 7 | 110 | Biopsy | Pending |
| 8 | 120 | Urine | Pending |
| 9 | 110 | Biopsy | Pending |
| 10 | 110 | Urine | Pending |
有我绕过通过mysqli的结果集具有循环的方式的客户,以便根据测试类型的名称并基于accountId获取每个测试类型的COUNT。因此,例如我目前做这个:
$sql = "SELECT C.accountId, A.companyName
FROM Customers C
JOIN Address A
ON C.addressId=A.addressId";
$result = mysqli_query($connection, $sql);
$customers = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach($customers as $customer) :
echo '<h2>' . $customer["companyName"] . '</h2>';
// Urine Tests Count
$sql = 'SELECT COUNT(testId) as count FROM Tests WHERE accountId=' . $customer["accountId"] . ' AND testType="Urine"';
$result = mysqli_query($connection, $sql);
$testCount = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo '<p>Total Urine Tests: ' . $testCount["count"] . '</p>';
// Biopsy Tests Count
$sql = 'SELECT COUNT(testId) as count FROM Tests WHERE accountId=' . $customer["accountId"] . ' AND testType="Biopsy"';
$result = mysqli_query($connection, $sql);
$testCount = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo '<p>Total Biopsy Tests: ' . $testCount["count"] . '</p>';
// Blood Tests Count
$sql = 'SELECT COUNT(testId) as count FROM Tests WHERE accountId=' . $customer["accountId"] . ' AND testType="Blood"';
$result = mysqli_query($connection, $sql);
$testCount = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo '<p>Total Blood Tests: ' . $testCount["count"] . '</p>';
endforeach;
正如你可能会说这是海拉但却难免重复,但到目前为止,它已经得到我想要的信息的唯一途径。我知道我可以做一个COUNT()
与GROUP BY
为测试一旦我在foreach循环内,但如果我这样做,我不会回0测试,客户可能没有,我需要显示,如果testType有0.
我很熟悉PhP,然后我在MySQLi和SQL中。有什么我在这里失踪?当然,必须有更好的方法来获得所有这些,甚至可以在一个查询中得到它?任何建议或正确方向的一点都会很棒。
如果我得到错误列'测试类型'在字段列表中含糊不清'什么可能导致这一点。 –
对不起,在交叉连接后需要别名Z.TestType(在select和group by中)。 – xQbert
没问题,我是否需要添加'COUNT(不同的T.testId)'以及否? –