从交叉引用表中获取唯一值

时间:2016-11-15 17:59:34

标签: php mysql pdo

现在我有一个交叉引用表,如下所示:

       Table job2pos
╔═══════════╦═════════════╗
║  job_id   ║ position_id ║
╠═══════════╬═════════════╣
║  1        ║  10         ║
║  2        ║  10         ║
║  2        ║  12         ║
║  3        ║  11         ║
║  3        ║  13         ║
║  4        ║  10         ║
║  5        ║  13         ║
╚═══════════╩═════════════╝

我想选择包含job_idpostion_id = 10的所有position_id = 12,这会产生job_id = 1,2,2,4。但我只希望job_id = 2在我提取的结果中只出现一次。

我尝试过的代码如下:

$positions = ["10","12"];

$sql = "SELECT job2pos.job_id FROM job2pos
WHERE job2pos.pos_id IN (?,?)";

$stmt = $pdo->prepare($sql);

foreach ($positions as $key => &$val) {
  $stmt->bindParam($key, $val, \PDO::PARAM_INT);
}

$stmt->execute();

var_dump($stmt->fetchAll(\PDO::FETCH_UNIQUE));

以上尝试将产生以下结果:

array(3) {
  [1]=> array(0) {}
  [2]=> array(0) {}
  [4]=> array(0) {}
}

所以我确实得到了唯一的值,而额外的2没有重复,但是我如何设置它以使job_id不作为索引出现而是作为数组边的值?

  • P.S。如果你能在我的代码中指出任何不必要的代码也会很棒。

1 个答案:

答案 0 :(得分:2)

特殊SELECT DISTINCT构造只会从您的查询中带来不同的值。因此,您可以将代码重写为:

$postions = ["10","12"];
$sql = "SELECT DISTINCT job2pos.job_id FROM job2pos WHERE job2pos.pos_id IN (?,?)";
$stmt = $pdo->prepare($sql);

// btw you don't have to bind elements one by one
// you can pass array as an argument to execute:
$stmt->execute($positions);

print_r($stmt->fetchAll(\PDO::FETCH_ASSOC));