从表中选择存在数组所有值的行

时间:2012-02-15 16:40:16

标签: mysql

我有这个查询来检索id + NAME的列表:

$sql = "SELECT id FROM #__table1 ";

$sql .= " WHERE (";
foreach($explode_tags as $k=>$explode_tag) {
  $sql .= "name = ".$db->Quote(trim($explode_tag));
  if(($k+1) != count($explode_tags))
  $sql .= " OR ";
}
$sql .= ")";        

$db->setQuery($sql);
$results = $db->loadResultArray();  

结果是这样的数组:

keywordID    |    NAME
1                 cat
2                 dog
3                 horse

现在我有了这个表2:

id   |    ItemID    |    keywordID
1            4              1
2            4              2
3            4              3
4            6              1
5            6              2
6            7              1

我想从table2中找到所有在table1中找到所有keywordID的ItemID。 在上面的例子中,我想只返回包含所有关键字的itemID 4(全部3个)。

我正在运行此查询,但我没有得到结果:

...
$query .= " AND i.id IN (SELECT itemID FROM #__table2 WHERE (";
foreach($results as $k=>$result) {
$query .= "keywordID = ".(int)$result;
if(($k+1) != count($results))
$query .= " AND ";
}
$query .= "))";     

3 个答案:

答案 0 :(得分:2)

<强>更新

抱歉,我想念您的问题。我使用这些数据进行了简单的测试:

id  itemId  keywordId
1   4       1
5   4       2
6   4       3
7   5       2
8   5       3
9   6       1
10  6       2
11  6       3
12  7       3
13  9       3
14  9       2
15  9       1

并使用此查询:

SELECT itemId, GROUP_CONCAT( keywordId ORDER BY keywordId ) AS crpcnct, COUNT( itemId ) 
FROM  `temporary_table_123` 
GROUP BY 1 
HAVING crpcnct =  '1,2,3' 

我可以获得你想要的价值:

itemId  crpcnct  count(itemId)
4       1,2,3    3
6       1,2,3    3
9       1,2,3    3

要实现这一点,您所要做的就是构建您要使用的keywordID:

$keywordIds[] = $results['keywordId'];

然后对加入

进行排序
sort($keywordIds);

最后一步是,将此数组提供给查询:

SELECT itemId, GROUP_CONCAT( keywordId ORDER BY keywordId ) AS crpcnct, COUNT( itemId ) 
FROM  `temporary_table_123` 
GROUP BY 1 
HAVING crpcnct =  '" . implode(",", $keywordIds) . "'

你有它。

答案 1 :(得分:0)

SELECT ItemID FROM table2 WHERE keywordID IN (SELECT keywordID FROM table1)

这可能有用。不过,我必须创建表的本地副本才能确定。

答案 2 :(得分:0)

$array_names = array();
foreach($explode_tags as $k=>$explode_tag){
    $array_names[] = 'name = ' . $db->Quote(trim($explode_tag));
}

$sql = "SELECT ItemID FROM table_2 WHERE keywordID IN (SELECT keywordID FROM table_1 WHERE " . implode(' OR ', $array_names) .")";
$db->setQuery($sql);
$results = $db->loadResultArray();