I need a query that returns order IDs that has mentioned in the comments certain word. I have three separate queries I want to merge then into one. So the result will be that I’ll get orders IDs only after a certain date and only if they have in comments more than 2 matches for the searched string.
How do I join them together?
First query getting orders IDs after a certain date
SELECT ID FROM `wp_posts` WHERE `post_date` > '2022-02-01 10:14:50' AND `post_status` = 'wc-completed' AND `post_type` = 'shop_order'
Second that returns only IDs when the comment contains searched string
SELECT comment_post_ID FROM `wp_comments` WHERE `comment_post_ID` in ( SELECT ID FROM `wp_posts` WHERE `post_date` > '2022-02-01 10:14:50' AND `post_status` = 'wc-completed' AND `post_type` = 'shop_order') AND `comment_content` LIKE '%searched string%'
Third return ID only if an order has at least 2 comments with searched string
SELECT comment_post_ID FROM `wp_comments` WHERE `comment_post_ID` = 466416 AND `comment_content` LIKE '%searched string%' having count(*) > 1
Fourth, combining all three previous doesn’t work
SELECT * FROM `wp_comments` WHERE `comment_post_ID` in ( SELECT ID FROM `wp_posts` WHERE `post_date` > '2022-02-01 10:14:50' AND `post_status` = 'wc-completed' AND `post_type` = 'shop_order' GROUP BY `comment_post_ID`) AND `comment_content` LIKE '%searched string%' having count(*) > 1
2
Answers
Try and struture your SQL for easy reading;
How about a subquery?