如何只返回出现在2个sql select语句中的项


How to return only items that occur in 2 sql select statemnts

我有两个不同的sql语句。$sql获取标题与某个搜索文本匹配的所有项目。CCD_ 2获取在某一类别中的所有CCD_。一个项目有一个ID。category_item有一个名为item_id的字段,它是items表中ID的外键

...
mysqli setup code
...
$title = $_POST["title"];
$cat_id = $_POST["cat_id"];
$cat_sql = "SELECT * FROM category_items WHERE category_id = '".$cat_id."'";
$sql = "SELECT * FROM items where title LIKE '%". $title ."%' Limit 70";
if (!$result_cat = $mysqli->query($cat_sql)) {
// The query failed. 
    echo "<h2 >ERROR</h2>";
    exit;
}
if (!$result = $mysqli->query($sql)) {
// The query failed. 
    echo "<h2 >ERROR</h2>";
    exit;
}

然后我显示所有项目:

while ($item = $result->fetch_assoc()) {
    include 'item_card.php';
}

目前,它只显示$sql查询中提取的所有项目。有没有办法从$result中删除所有ID在$result_cat中没有表示为item_id的项目?

注意:我强烈希望不要将两个SELECT语句合并到一个表联接中,因为实际的$sql和$cat_sql并不像我在这里所说的那么简单。此外,它们也因所在的if语句而异。

我的问题是:给定$result$result_cat,我可以从$result中删除项目吗?

编辑1根据评论的建议,我正在制作一个if-item_ids数组,然后进行in_array查询。迄今为止的进展:

$result_cat_ids = [];
while ($cat_item = $result_cat->fetch_assoc()) {
    $result_cat_ids[] = $cat_item['item_id'];
}

编辑2以下是评论中建议的工作代码

  if (in_array($item['id'], $result_cat_ids)) {
      include 'item_card.php';
  }

您也可以使用'INTERSECT'sql子句。

$sql = "SELECT * FROM items WHERE id IN (SELECT item_id FROM category_items WHERE category_id = '".$cat_id."' INTERSECT SELECT id FROM items where title LIKE '%". $title ."%')";

通过这种方式,您可以查询满足这两个条件的项。

注意:我没有使用"limit70",但您也可以添加它。