从表中选择值不存在

时间:2012-12-05 03:01:08

标签: php mysql select

我有一张表格(country_table),其中列出了所有国家/地区及其各自的ID。

|country_id|country_name|
|ES        |Spain       |
.
.
.

我有一个数组,使用fetch_array从另一个表中获取,如下所示:

$array = Array(
    [0]=>Array([country_id]=>'ES')
    [1]=>Array([country_id]=>'DE')
    [2]=>Array([country_id]=>'GB'))

如何从country_table中选择表中不存在但存在于数组中的记录(country_id和country_name)?

4 个答案:

答案 0 :(得分:2)

$sql ="SELECT country_id, country_name FROM country_table
       WHERE country_id NOT IN (". implode(",", $array) .")";

implode()函数将生成数组元素的逗号分隔字符串表示。

答案 1 :(得分:0)

这是sql。

select country_id, country_name from table where country_id not in ('ES','DE','GB');

答案 2 :(得分:0)

// gather unwanted id's first
$notInIds = array();
foreach ($array as $arr) $notInIds[] = $arr['country_id'];

// prepare query
$query = 'SELECT `country_id`, `country_name` FROM `your_table`
WHERE `country_id` NOT IN (' . implode(',',$notInIds) . ')';

// then execute it

答案 3 :(得分:0)

对于问题:“我如何从country_table 中选择表中存在存在于数组中的记录(country_id和country_name) ?“

我想你必须编写一些代码(例如在PHP中)以获得你想要的结果。 问题是您无法显示表中没有的数据(例如country_name),这是不可能的,因为您不知道这些数据。唯一的可能性是显示country_id是在数组中而不在表中,因为这是您拥有的唯一数据...