简体   繁体   English

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

[英]mysql - check if a group of elements are included in another group

I have the following setup: 我有以下设置:

An array in php like this: 像这样的PHP数组:

 $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). 子查询返回类似(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). 我不想做的是在php中获取数据并在那里检查(这只是一个非常小的一个巨大的查询部分)。

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: 如果我正确理解您的问题,我认为这将是您测试数组中所有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;

?>

Mysql will return empty results if the HAVING count = $myArrayCount; 如果HAVING count = $ myArrayCount, Mysql将返回空结果; does not match the number of IDs you are checking for. 与您要检查的ID数量不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM