D
D
denism3002019-12-26 19:47:19
SQL
denism300, 2019-12-26 19:47:19

How to check if an element is in two arrays in SQL?

There is a request:

SELECT ID 
FROM wp_posts 
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) 
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) 
WHERE wp_term_relationships.term_taxonomy_id IN (43)
AND
wp_term_relationships.term_taxonomy_id IN (89)

However, it produces an empty result.
But if you make a query like:
SELECT ID 
FROM wp_posts 
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) 
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) 
WHERE wp_term_relationships.term_taxonomy_id IN (43)

or
SELECT ID 
FROM wp_posts 
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) 
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) 
WHERE wp_term_relationships.term_taxonomy_id IN (43)

then the same IDs are displayed.
How to fix the query if you need to take into account that the ID must belong to both an array, which can be instead of 43, and an array, which can be instead of 89?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2019-12-26
@denism300

SELECT *
  FROM `wp_posts`
  WHERE `ID` IN (
    SELECT `object_id`
      FROM `wp_term_relationships`
      WHERE `term_taxonomy_id` IN (43, 89)
      GROUP BY `object_id`
      HAVING COUNT(*) = 2
    )

D
d-stream, 2019-12-26
@d-stream

while the general request sounds "stop there, come here" the value will never be both 43 and 89
, but if you wrap the last two requests in exists, then you can already get what you want:
if exists(select...where 43) and exists( select ... where 89) - will give a positive result if the data is in both the first and second queries,
or I can offer perverted options with union)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question