我在表中有 2 列,我想從所有第 2 列的第一列中搜索每一行的重復項。所以我想找出第 1 列中的每一行是否存在于所有第 2 列中。我指定我的表很大,有 3 百萬行。我的表名是 bigquerry,有 2 列:id1 和 id2
uj5u.com熱心網友回復:
使用 aJOIN將表鏈接回自身和JOINID 欄位。
假設一個簡單的表是這樣的:
| ID | 編號1 | 編號2 |
|---|---|---|
| 1 | 一種 | 乙 |
| 2 | C | D |
| 3 | 乙 | F |
| 4 | G | 一種 |
| 5 | H | C |
| 6 | 一世 | 一種 |
| 7 | J | 一種 |
| 8 | 鉀 | C |
| 9 | 升 | F |
您可以使用此查詢提取重復項:
select a.id, a.id1, b.id, b.id2 from duplicates a join (select id, id2 from duplicates) b on a.id1 = b.id2;
輸出:
| ID | 編號1 | ID | 編號2 |
|---|---|---|---|
| 1 | 一種 | 4 | 一種 |
| 1 | 一種 | 6 | 一種 |
| 1 | 一種 | 7 | 一種 |
| 2 | C | 5 | C |
| 2 | C | 8 | C |
注意確保您已索引該id2列,否則這可能需要很長時間。
演示:https : //www.db-fiddle.com/f/fbZiyxa7fSzZFDhm9BS32L/1
uj5u.com熱心網友回復:
干得好
<?php
//set time limit to indefinite to parse the 3m rows
set_time_limit(0);
$conn = new mysqli("localhost", "username", "password", "db_name");
$id1list = $conn->query("SELECT id1 FROM `bigquery`");
//loop through all id1 returned by the query
while($r = mysqli_fetch_assoc($id1list)) {
$id1 = $r['id1'];
//get the count of id2 which are equal to the current id1
$id2count = $conn->query("SELECT count(id2) FROM `bigquery` WHERE id2='$id1'");
$count = mysqli_fetch_array($id2count)[0];
//print if count is greater than 0 (exists in id2)
if($count>0){
echo "$id1 is repeated $count times. <br>";
}
}
?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352672.html
