dth981485742 2013-07-24 13:13
浏览 444
已采纳

mysql - 检查一组元素是否包含在另一个组中

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).

  • 写回答

1条回答 默认 最新

  • dstew32424 2013-07-24 13:54
    关注

    If I'm understanding your question correctly, I think this would be the easiest way for you to test that all IDs in your array match to a record in the database:

    <?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;
    
    ?>
    

    Mysql will return empty results if the HAVING count = $myArrayCount; does not match the number of IDs you are checking for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog