Question

The Query is this one:

    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

My problem is the second join: It joins the same table again to add a column with the content "arbeitsregion_bis". The result should be something like this:

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

But the result of the query is always no entry. Why?

EDIT: I dont need the values, I only need those in the WHERE conditions, sry.

Was it helpful?

Solution

With the join you're doing, you're assuming that meta.name has two values at the same time, 'arbeitsregion_von' and 'arbeitsregion_bis', which is not possible.

This query should give you what you want (in two rows per user though).

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')

To have it in one column, you'd have to pivot:

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

EDIT: To meet your new requirements it'd be easiest to do

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top