[英]MySQL, PHP: Select * from table where id is not in array
所以我目前有一個數據庫表,我試圖選擇所有記錄除了那些包含在我已經制作的數組中的記錄。 作為一些背景背景:
有問題的數據庫表的結構是:
server_status:
id int(11)
server_id int(11)
time_checked datetime
status char(1)
將數據導入哈希的PHP腳本如下所示:
$sql2 = "SELECT server_id, time_checked,id from server_status where time_checked<'$date' order by server_id;";
$result2=$conn->query($sql2);
while($row2 = $result2->fetch_assoc()){
$server_id = $row2['server_id'];
$id = $row2['id'];
$dt = $row2['time_checked'];
$year = substr($dt,0,4);
$month = substr($dt,5,2);
$day = substr($dt,8,2);
$day = "$year-$month-$day";
$all[$server_id][$day] = $id; // ARRAY
}
所以我要做的是創建一個MySQL查詢,從數組中讀取id($ id),並從中選擇* APART。 從查找起來,似乎我將不得不使用'where not'子句,但我不知道如何引用哈希。
進一步澄清:我現在有一個數組,它提取如下所示的數據:
1{
2016-05-05 : 252
2016-05-10 : 406
2016-04-27 : 141
2016-05-04 : 164
2016-05-09 : 263
2016-05-03 : 153
2016-04-26 : 131
2016-04-14 : 1
2016-04-18 : 31
2016-04-21 : 111
2016-04-20 : 61
2016-04-19 : 51
2016-04-15 : 21
2016-04-25 : 121
}
2{
2016-05-10 : 452
2016-05-05 : 198
2016-05-09 : 264
2016-05-04 : 165
2016-04-26 : 132
2016-04-27 : 143
2016-04-25 : 122
2016-04-21 : 112
2016-05-03 : 154
}
我想從這個數組中獲取ID(例如154)並選擇表中沒有任何上述ID的所有內容。 我希望這有助於澄清?!
任何幫助將不勝感激!
如果$all
是要從中提取不需要的ID的數組,這可能是您提供的代碼后所需的內容:
$ids_to_exclude = array();
// iterate through servers
foreach ($all as $server_id => $dates) {
// iterate through dates of each server
foreach ($dates as $date => $id) {
// If a value is not in the array, add it.
// In case ids don't repeat, you won't need this if
if (!in_array($id, $ids_to_exclude)) {
// add $id to the array
$ids_to_exclude[] = $id;
}
}
}
$sql_condition = "where `id` not in (".implode(",",$ids_to_exclude).")";
我想你只想要一個NOT IN,對嗎?
$sql2 = "SELECT id, server_id, time_checked,id
FROM server_status
WHERE
id NOT IN (".implode(',', $id_array)."
AND time_checked<'$date'
ORDER BY server_id;";
$result2=$conn->query($sql2);
while($row2 = $result2->fetch_assoc()){
$server_id = $row2['server_id'];
$id = $row2['id'];
$dt = date('Y-m-d', strtotime($row2['time_checked']));
$all[$server_id][$dt] = $id; // ARRAY
}
解決:
$sql2 = "SELECT server_id, time_checked,id from server_status where time_checked<'$date' order by server_id;";
$result2=$conn->query($sql2);
while($row2 = $result2->fetch_assoc()){
while($row2 = $result2->fetch_assoc()){
$server_id = $row2['server_id'];
$id = $row2['id'];
$dt = date('Y-m-d', strtotime($row2['time_checked']));
$all[$server_id][$dt] = $id; // ARRAY
}
}
$stack = array();
$keys = array_keys($all);
for($i = 0; $i < count($all); $i++) {
foreach($all[$keys[$i]] as $key => $value) {
array_push($stack, $value);
}
}
$ids = join(',',$stack);
$sql = "SELECT * FROM server_status WHERE time_checked<'$date' AND id NOT IN ($ids)";
$result=$conn->query($sql);
echo "Server status data has been deleted.<br>";
從多維數組中創建另一個數組以僅存儲id,並使用像John Green建議的NOT IN。
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.