Sql (zend db select) of multiple selects
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.
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)
精彩评论