0

查询是这个:

    SELECT resume.user_id
    FROM ".$wpdb->prefix."wpjb_meta as meta
    JOIN ".$wpdb->prefix."wpjb_meta_value as value_von
    ON meta.id = value_von.meta_id AND meta.meta_object = 'resume' AND meta.name = 'arbeitsregion_von'
    JOIN ".$wpdb->prefix."wpjb_meta_value as value_bis
    ON meta.id = value_bis.meta_id AND meta.meta_object = 'resume' AND meta.name = 'arbeitsregion_bis'          
    JOIN ".$wpdb->prefix."wpjb_resume as resume
    ON value_bis.object_id = resume.id
WHERE value_von.value <= 222222 AND value_bis.value >= 222222

我的问题是第二次加入:它再次加入同一个表以添加内容为“arbeitsregion_bis”的列。结果应该是这样的:

resume.user_id
-------4-------
-------6-------

但是查询的结果始终是没有条目。为什么?

编辑:我不需要这些值,我只需要 WHERE 条件下的值,sry。

4

1 回答 1

2

通过您正在进行的连接,您假设它meta.name同时具有两个值,“arbeitsregion_von”和“arbeitsregion_bis”,这是不可能的。

这个查询应该给你你想要的(虽然每个用户有两行)。

SELECT resume.user_id, meta.name as von_bis, my_values.value
FROM ".$wpdb->prefix."wpjb_meta as meta
JOIN ".$wpdb->prefix."wpjb_meta_value as my_values
ON meta.id = my_values.meta_id AND meta.meta_object = 'resume'
JOIN ".$wpdb->prefix."wpjb_resume as resume
ON my_values.object_id = resume.id
WHERE
meta.name IN ('arbeitsregion_von', 'arbeitsregion_bis')

要将它放在一列中,您必须旋转:

SELECT resume.user_id, 
MAX(CASE WHEN meta.name = 'arbeitsregion_von' THEN my_values.value END) AS von,
MAX(CASE WHEN meta.name = 'arbeitsregion_bis' THEN my_values.value END) AS bis
FROM ".$wpdb->prefix."wpjb_meta as meta
JOIN ".$wpdb->prefix."wpjb_meta_value as my_values
ON meta.id = my_values.meta_id AND meta.meta_object = 'resume'
JOIN ".$wpdb->prefix."wpjb_resume as resume
ON my_values.object_id = resume.id
WHERE
meta.name IN ('arbeitsregion_von', 'arbeitsregion_bis')
GROUP BY resume.user_id

编辑:为了满足您的新要求,最容易做到

SELECT resume.user_id, 
MAX(CASE WHEN meta.name = 'arbeitsregion_von' THEN my_values.value END) AS von,
MAX(CASE WHEN meta.name = 'arbeitsregion_bis' THEN my_values.value END) AS bis
FROM ".$wpdb->prefix."wpjb_meta as meta
JOIN ".$wpdb->prefix."wpjb_meta_value as my_values
ON meta.id = my_values.meta_id AND meta.meta_object = 'resume'
JOIN ".$wpdb->prefix."wpjb_resume as resume
ON my_values.object_id = resume.id
WHERE
meta.name IN ('arbeitsregion_von', 'arbeitsregion_bis')
GROUP BY resume.user_id
HAVING von <= 222222  AND bis >= 222222 
于 2013-09-17T08:51:18.713 回答