我试图通过MySQL上的同一个表中的另一个字段查找字段数。我的表格如下:
Code Helper_I_Count Helper_A_Count
T151 3 1
所以我想找到T151使用的辅助代码,IsPrincipal等于1。
输出应该是这样的:
SELECT t.`Code`,COUNT(v1.`Code`) AS EkTaniSay,COUNT(v2.`Code`) AS IslemSay
FROM TIGPatientCode t,
(
SELECT DRGPatientId,`Code`
FROM TIGPatientCode
WHERE IsPrincipal<>'1' AND CodeType='I'
) v1,
(
SELECT DRGPatientId,`Code`
FROM TIGPatientCode
WHERE IsPrincipal<>'1' AND CodeType='A'
) v2
WHERE t.IsPrincipal='1' AND t.DRGPatientId=v1.DRGPatientId AND t.DRGPatientId=v2.DRGPatientId
GROUP BY t.`Code`
所以我尝试了这样:
<div class="dropdown">
<button onclick="myFunction()" class="dropMenu"><span class="col_blue">Welcome:</span> <?php echo $_SESSION['username']; ?></button>
<div id="myDropdown" class="dropdown-content">
<form class="form">
<div class="switch-field">
<div class="switch-title">Make Resume Public?</div>
<input type="radio" id="switch_left" name="switch_2" value="yes" checked/>
<label for="switch_left">Yes</label>
<input type="radio" id="switch_right" name="switch_2" value="no" />
<label for="switch_right">No</label>
</div>
</form>
<?php
$switch_2 = $_POST['switch_2'];
$qry = "UPDATE resumes SET public = :public WHERE memberID = :memberID";
$stm = $db->prepare($qry);
$stm->bindParam(':public', $switch_2, PDO::PARAM_STR);
$stm->bindParam(':memberID', $uid, PDO::PARAM_STR);
$stm->execute();
?>
<?php
$stmt = $db->prepare("select * from jobs where jobposterID = '".$_SESSION['memberID']."'");
$stmt->execute();
$jobs = $stmt->rowCount();
?>
<a href="<?php echo DIR; ?>my-jobs.php"><i class="fa fa-suitcase"></i> MY JOBS (<?php echo $jobs; ?>) </a>
<a href="<?php echo DIR; ?>applied-jobs.php"><i class="fa fa-check-square-o"></i> APPLIED JOBS </a>
<a href="<?php echo DIR; ?>viewed-jobs.php"><i class="fa fa-eye"></i> VIEWED JOBS </a>
<a href="<?php echo DIR; ?>logout.php"><i class="fa fa-power-off"></i> LOGOUT </a>
</div>
</div>
但它不会得到实际数字。
我该怎么做?
由于
答案 0 :(得分:1)
SELECT t2.Code,
SUM(t1.CodeType = 'I') AS EkTaniSay,
SUM(t1.CodeType = 'A') AS IslemSay
FROM TIGPatientCode AS t1
RIGHT JOIN TIGPatientCode AS t2 ON t1.DrgPatientId = t2.DrgPatientId
WHERE t1.isPrincipal != 1 AND t2.isPrincipal = 1
GROUP BY t1.DrgPatientId;
查询的第一部分基于multiple query same table but in different columns mysql。然后我再次与表连接以获取主行的代码。
您的查询的问题是加入两个子查询会创建所有行的叉积,这会导致计数成倍增加。此外,如果有任何组没有其中一个代码,则该子查询将不返回任何行,因此该代码的连接将为空。您可以通过在子查询中进行计数而不是主查询来修复第一个问题。可以使用LEFT JOIN
修复第二个问题。因此,查询的固定版本如下所示:
SELECT t.Code, v1.EkTaniSay, v2.IslemSay
FROM TIGPatientCode t
LEFT JOIN (
SELECT DRGPatientId, COUNT(*) AS EkTaniSay
FROM TIGPatientCode
WHERE IsPrincipal<>'1' AND CodeType='I'
GROUP BY DRGPatientId
) AS v2 ON t.DRGPatientId = v2.DRGPatientId
LEFT JOIN (
SELECT DRGPatientId, COUNT(*) AS IslemSay
FROM TIGPatientCode
WHERE IsPrincipal<>'1' AND CodeType='A'
GROUP BY DRGPatientId
) AS v1 ON t.DRGPatientId = v1.DRGPatientId
WHERE t.IsPrincipal = 1