Reputation: 949
I want to select a post only if $arr_tags
match all 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
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
Upvotes: 2
Views: 8472
Reputation: 57093
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. Most recently, Chris Date has proposed replacing the whole concept with image relations.
SQL has no explicit divide operator. 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.
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
Upvotes: 0
Reputation: 255155
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
Upvotes: 4