简体   繁体   English

匹配查询中数组的元素

[英]Match the elements of array in query

I want to select a post only if $arr_tags match all array_elements with tags_is_tags . 我只想选择$arr_tags$arr_tags匹配所有array_elements with tags_is_tags For example in this situation will be outputted 0 posts because one array element didn't match with tags_id_tags 例如在这种情况下将输出0个帖子,因为一个数组元素与tags_id_tags不匹配

How can i do something like that ? 我该怎么做?

$arr_tags = array("16", "17", "36", "543"); // the dimension is not always the same

post_id_post        tags_id_tags    
    282                      16     
    282                      17     
    282                      36 
    282                      546 

I have this code but the query is not finished. 我有此代码,但查询尚未完成。

            $sql = $db -> prepare("
                SELECT post_id_post 
                FROM posts
                // ...
            ");

            $sql -> bind_param('s', $val);
            $sql -> execute();
            $sql -> bind_result($d_post);

Thanks for your time 谢谢你的时间

  SELECT post_id_post
    FROM posts
   WHERE tags_id_tags IN ("16", "17", "36", "543")
GROUP BY post_id_post
  HAVING COUNT(*) = 4

You put all the required tags' IDs in the IN clause and change the number in COUNT(*) = 4 expression to the number of tags passed 您将所有必需标签的ID放在IN子句中,并将COUNT(*) = 4表达式中的数字更改为传递的标签数

It seems to me that as much as anything you want to know how to ask the right question. 在我看来,您想知道如何提出正确的问题之多。 The magic words here are "relational division". 这里的魔术词是“关系划分”。

It is one of the operators in Codd 's relational algebra and there have been several variations proposed since. 它是Codd 关系代数中的运算符之一,此后提出了几种变体。 Most recently, Chris Date has proposed replacing the whole concept with image relations . 最近, 克里斯·伊达特( Chris Date )提出用图像关系代替整个概念。

SQL has no explicit divide operator. SQL没有明确的除法运算符。 There are a number of workarounds using other operator and the most appropriate will depend on your requirements, including exact division or division with remainder and how to handle an empty divisor. 使用其他运算符有多种解决方法,最合适的方法取决于您的要求,包括精确除法或除法除法,以及如何处理空除数。 Then there are the usual considerations: SQL product and version, performance, personal style and taste, etc. 然后是通常的注意事项:SQL产品和版本,性能,个人风格和品味等。

Here are a couple of articles which should help you with these choices: 这里有几篇文章可以帮助您进行以下选择:

On Making Relational Division Comprehensible 关于关系划分的理解

Divided We Stand: The SQL of Relational Division 分开的立场:关系部门的SQL

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

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