0

I have the following setup:

An array in php like this:

 $arr = array(1, 2, 3, 4);

A query that looks like this:

 SELECT `epicThing` FROM `epicTable` AS `epic`
 WHERE
     SELECT `ids` FROM `someTable` 
     WHERE `epic`.`somethingSomething` = `someTable`.`somethingElse`
     (<<<< HERE IS MY PROBLEM >>>>)

The subquery returns something like (1, 2, 3, 4, 5, 6, 7, 8, 9).

Now what I need to check is that each of the elements from the array is in that returned answer of the subquery.

Basically something like

 SELECT `epicThing` FROM `epicTable` AS `epic`
 WHERE
     '1' IN (
         SELECT `ids` FROM `someTable` 
         WHERE `epic`.`somethingSomething` = `someTable`.`somethingElse`
      )
 AND 
     '2' IN (
         SELECT `ids` FROM `someTable` 
         WHERE `epic`.`somethingSomething` = `someTable`.`somethingElse`
      )
 AND
     '3' IN (
         SELECT `ids` FROM `someTable` 
         WHERE `epic`.`somethingSomething` = `someTable`.`somethingElse`
      ).......

But for each element.

For simplicity let's assume that elements are always in order (because I will probably need to convert the array to string), if is not possible otherwise. But I would prefer a general solution if available.

What I DON'T want to do is to get data in php and check it there (this is only a really really small part of a huge query).

4

1 回答 1

2

如果我正确理解了您的问题,我认为这将是您测试数组中的所有 ID 是否与数据库中的记录匹配的最简单方法:

<?php
    $myArray = array(1,2,3);
    $myArrayCount = count($myArray);

    // Convert array for the query
    $queryArray = implode(",", $myArray);

    SELECT COUNT(DISTINCT(YourTable.id)) AS count
    FROM YourTable
    WHERE YourTable.id IN ($queryArray)
    HAVING count = $myArrayCount;

?>

如果HAVING count = $myArrayCount;则 Mysql 将返回空结果 与您要检查的 ID 数量不匹配。

于 2013-07-24T13:54:02.563 回答