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 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab