我想在一个sql查询中联接2个表(contact和contact_meta),知道contact_meta
有几行
联系
id fname lname email
1 Nick John njohn@gmail.com
2 Laura Pitt lpitt@gmail.com
Contact_meta
id_contact contact_meta_key contact_meta_value
1 Newsletter yes
1 Level weak
2 Newsletter yes
我尝试过
SELECT * FROM contact as c
JOIN contact_meta as cm ON c.id = cm.id_contact
但是如果contact_meta中有多行,我只会得到最后一行。
Array (
[0] => stdClass Object ( [id] => 1 [lname] => Nick [fname] => John [email] => njohn@gmail.com [contact_meta_key] => level [contact_meta_value] => weak )
[1] => stdClass Object ( [id] => 2 [lname] => Laura [fname] => pitt [email] => lpitt@gmail.com [contact_meta_key] => newsletter [contact_meta_value] => yes
);
此外,我想要[newsletter] => yes instead of [contact_meta_key] => newsletter [contact_meta_value] => yes
我所希望的:
Array (
[0] => stdClass Object ( [id] => 1 [lname] => Nick [fname] => John [email] => njohn@gmail.com [level] => weak [newsletter] => yes)
[1] => stdClass Object ( [id] => 2 [lname] => Laura [fname] => pitt [email] => lpitt@gmail.com [newsletter] => yes
);
答案 0 :(得分:1)
您需要透视元表。
SELECT c.*,
MAX(IF(contact_meta_key = 'Newsletter', contact_meta_value, NULL)) AS newsletter,
MAX(IF(contact_meta_key = 'Level', contact_meta_value, NULL)) AS level
FROM contact AS c
LEFT JOIN contact_meta AS cm ON c.id = cm.id_contact
GROUP BY c.id
答案 1 :(得分:0)
问题是今天John在contact_meta中有2个条目,但明天可能是5个,而Laura 9个,我在其中存储了许多数据。如果有可能通过1个SQL查询获得用户的所有元数据联系。
我找到了一个解决方案,但我认为不好,因为2条SQL查询(我使用Wordpress):
$ user = $ wpdb-> get_results(“ SELECT * FROM contact as c JOIN related_browser_contact as rbc ON c.contact_id = rbc.id_contact JOIN浏览器as b ON rbc.id_browser = b.browser_id”);
$fellows = array();
$i=0;
foreach ($user as $key => $value) {
$data=array();
foreach ($user[$i] as $key => $value) {
if ( Helper::encrypt_decrypt('decrypt', $value) ){
$data[$key] = Helper::encrypt_decrypt('decrypt', $value);
}else{
$data[$key] = $value;
}
$metas = $wpdb->get_results( "SELECT contact_meta_key, contact_meta_value FROM contact_meta WHERE id_contact = ".$user[$i]->contact_id );
foreach ($metas as $key => $value) {
$data[$value->contact_meta_key] = $value->contact_meta_value;
}
}
$fellows[] = $data;
$i++;
}
print_r($fellows);
在这种情况下,我拥有了所有想要的东西,但是只是想知道SQL查询是否可以做到...