0

I need a bit of help. I have (reference?) table with columns: id , user_id , key , value

It is pretty much a user profile table and I would like to have SQL (I am using zend db table, but general SQL help will do) where I get "all 'user_id's where 'key' is somekey and 'value' is somevalue of that user_id but only if it also matches where 'key' is otherkey and 'value' is othervalue".

In other words I want to get users that have shoes of maker NIKE and color BLACK. therefore 'key' is shoecolor and 'value' is BLACK and also another row with same user_id has 'key' is shoemaker and 'value' is NIKE.

This is what I could come up with, but doesn't work.

SELECT `user_profiles`.* FROM `user_profiles` WHERE
(`key` = 'shoecolor' AND `value` = 'BLACK') AND
(`key` = 'shoemaker' AND `value` = 'NIKE')

In case someone is knowledgable in zend db:

$where = array('shoecolor' => 'BLACK', 'shoemaker' => 'NIKE');
    foreach ($where as $key => $value) {
        $sql = $db->quoteInto('key = ?', $key);
        $sql .= ' AND ' . $db->quoteInto('value = ?', $value);
        $select->where($sql);
    }
    // make unique result
    //$select->groupBy('user_id');
    $resultSet = $zendTableInstance->fetchAll($select);

Please Help. Thanx.

1 Answer 1

1

Because the key/value pair is in the row, your query is looking for a key that is 3 AND 4. No value can be 3 and 4 at the same time ;)

SELECT user_profiles.* FROM user_profiles WHERE (key = 3 AND value = 21) AND (key = 4 AND value = 55)

will not work.

You could do a join on yourself, and check for these values?

SELECT user_profiles.* 
FROM user_profiles up1
  JOIN user_profiles up2 ON up1.user_id = up2.user_id
WHERE 
  (up1.key = 3 AND up1.value = 21) 
  AND (up2.key = 4 AND up2.value = 55)
Sign up to request clarification or add additional context in comments.

2 Comments

I believe you still need to add a join condition JOIN user_profiles up2 ON up1.user_id = up2.user_id
oops, you're right. I'm always forgetting that sort of stuff, although the general idea might be correct :) I'll add that, thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.