[英]Compare 2 tables and select data from one table
我有2個表lc_details
和reference
,並且這些表具有reference_no
列。 我想比較那些表,並在reference.reference_no
列中不存在lc_details.reference_no
情況下從reference
表中選擇reference_no
。
這是我的代碼,但它顯示了引用表中的所有數據,並重復了多次。
<table class="table table-striped">
<tr>
<th>Sl. No.</th>
<th>Reference No./th>
</tr>
<?php
include("../db/db.php");
$sql_cat="select b.* from lc_details a, reference b where b.reference_no!=a.reference_no' order by reference_no ASC";
$run_sql=mysqli_query($con, $sql_cat);
$i=0;
while($row_cat=mysqli_fetch_array($run_sql)){
$reference_no=$row_cat['reference_no'];
$i++;
?>
<tr align="center">
<td><?php echo $i; ?></td>
<td><?php echo $reference_no; ?></td>
</tr>
<?php } ?>
</table>
嘗試這個:
SELECT ref.*
FROM reference AS ref
LEFT JOIN lc_details AS lc_d
ON lc_d.reference_no = ref.reference_no
WHERE lc_d.reference IS NULL
ORDER BY ref.reference_no ASC
讓我解釋一下:
使用左聯接聯接表意味着,如果右表(在我們的示例中為lc_details表)的值或引用不存在於左表(在我們的示例中為“ reference”表),它將仍然得到記錄。 例如:
如果表A包含1、2、3和4的ID,而表B僅包含1、2和4的ID,則使用左連接將它們連接起來將產生如下結果:
A.id B.id
1 1
2 2
3 NULL
4 4
因此,添加一個僅檢查表b上具有空ID的where子句的結果為:
A.id B.id
3 NULL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.