2016-08-01 85 views
2

嘗試將兩個查詢合併到數組中。看看我的代碼,首先,我想讓所有的水果都有貓A和纈氨酸。第二,我會得到果匹配第一個查詢的標記,cat c和val可以是好或壞。最後,我想讓它們排列得像 $ arg =('apple'=>'4','banana'=>'2','pear'=>'0');因爲梨不符合val好或壞,所以0.你有什麼辦法做到這一點?欣賞。 試圖從MySQL查詢創建多維數組,PHP?

<?php 
 
/* 
 
fruit cat  val mark 
 
apple A  good V 
 
apple c  OK  4 
 
banana A  good  W 
 
banana c  bad  2 
 
pear A  good  W 
 
pear c  good  8 
 
*/ 
 
$val1 = 'OK'; 
 
$val2 = 'bad'; 
 
$result1 = $wpdb->get_results($wpdb->prepare(" 
 
\t SELECT DISTINCT fruit FROM my_table WHERE cat ='A' AND val='%s' ",$val1)); 
 

 
$result2 = $wpdb->get_results($wpdb->prepare(" 
 
\t SELECT mark FROM my_table WHERE cat ='c' AND val='%s' AND fruit IN (SELECT DISTINCT fruit FROM my_table WHERE cat ='A' AND val='%s')",$val2,$val1)); 
 

 
/*how can I combine these two queries into an array like 
 
$arg = ('apple'=>'4','banana'=>'2','pear'=>'0'); 
 
because pear did not match, so 0 
 
*/ 
 
?>

回答

0

最簡單的辦法是重寫,而不是做在PHP手動查詢,我認爲這會做你想要什麼:

SELECT 
    t.fruit, 
    CASE 
    WHEN t.a_mark IS NOT NULL THEN t.a_mark 
    WHEN t.c_mark IS NOT NULL THEN t.c_mark 
    ELSE '0' 
    END mark 
FROM 
    (SELECT 
    t.fruit, 
    (SELECT MAX(mark) 
     FROM my_table 
     WHERE fruit = t.fruit AND val = 'good' AND cat = 'A' 
     AND mark NOT IN ('V', 'W')) a_mark, 
    (SELECT MAX(mark) 
     FROM my_table 
     WHERE fruit = t.fruit AND val in ('OK', 'bad') AND cat = 'c' 
     AND mark NOT IN ('V', 'W')) c_mark 
    FROM 
    (SELECT DISTINCT fruit FROM my_table) t 
) t 
ORDER BY 
    t.fruit