如何添加以在主查询中选择多个子查询值

时间:2014-12-22 06:40:04

标签: php mysql wordpress

查询:

SELECT *
FROM `wp_posts`
WHERE `ID`
IN GROUP_CONCAT(
(
SELECT post_id
FROM `wp_postmeta`
WHERE `meta_key` = 'friday_happy_hour_start_time'
AND `meta_value` <= '9'
) && (
SELECT post_id
FROM `wp_postmeta`
WHERE `meta_key` = 'friday_happy_hour_end_time'
AND `meta_value` >= '9'
)
)

子查询1和2有多个结果,所以我使用了GROUP_CONCAT()。但它不起作用。 我希望所有帖子中9等于或meta_value('s)meta_key ='friday_happy_hour_end_time'和meta_key ='friday_happy_hour_start_time'。请向我提供解决方案

3 个答案:

答案 0 :(得分:0)

无需使用group_concat和多个子查询,只需将wp_postmeta两次加入帖子并定义您的条件即可轻松完成此操作

SELECT p.* 
FROM `wp_posts` p
JOIN wp_postmeta m ON(p.ID = m.post_id)
JOIN wp_postmeta m1 ON(p.ID = m1.post_id)
WHERE m.`meta_key` = 'friday_happy_hour_start_time' 
AND m1.`meta_key` = 'friday_happy_hour_end_time' 
AND m.`meta_value` <= '9' 
AND m1.`meta_value` >= '9'

答案 1 :(得分:0)

我认为不是使用group_contact,而是可以在单个子查询中实现所需。 括号是这里的重要因素。

SELECT *
FROM `wp_posts`
WHERE `ID`
IN (
SELECT post_id
FROM `wp_postmeta`
WHERE 
(`meta_key` = 'friday_happy_hour_start_time' AND `meta_value` <= '9')  
OR 
(`meta_key` = 'friday_happy_hour_end_time' AND `meta_value` >= '9')

)-- End of IN

答案 2 :(得分:0)

SELECT *
FROM `wp_posts`
WHERE `ID` IN (
    SELECT DISTINCT post_id
    FROM `wp_postmeta`
    WHERE `meta_key` = 'friday_happy_hour_start_time'
    AND `meta_value` <= '9'

    UNION DISTINCT 

    SELECT DISTINCT post_id
    FROM `wp_postmeta`
    WHERE `meta_key` = 'friday_happy_hour_end_time'
    AND `meta_value` >= '9'
)