2012-02-20 196 views
2

所有子查詢返回多個1行

我有兩個表 enter image description here

1表:wp_frm_item_metas 第二表是:wp_frm_items

現在我想基於wp_frm_items表字段值meta_value 。

我解僱了這個sql。它返回我的子查詢返回超過1行

SELECT meta_value 
FROM wp_frm_item_metas 
WHERE (item_id=(
    SELECT id 
    FROM wp_frm_items 
    WHERE form_id ='9' && user_id='1') 
&& field_id=128) 

我試過這個解決方案

SELECT meta_value 
FROM wp_frm_item_metas 
WHERE (item_id=(
    SELECT count(*) as c,id 
    FROM wp_frm_items 
    WHERE form_id ='9' && user_id='1') 
&& field_id=128 && c > 1) 
ORDER BY c DESC 

它返回該錯誤操作數應包含1列(S)

我的代碼是

foreach($fp_id_c as $kid=>$id) 
{ 
    if (!$id or ($logged_in && !$user_ID)) return; 
    $id = (int)$id; 

    //echo $logged_in.'-'.(int)$user_ID; 
    if ($logged_in){ 
     echo $ff_id_c[$kid]; 
     global $wpdb; 
     echo "SELECT meta_value FROM wp_frm_item_metas WHERE (item_id=(SELECT count(*) as c,id FROM wp_frm_items WHERE form_id ='$kid' && user_id='". (int)$user_ID ."') && ORDER BY c DESC && field_id=$ff_id_c[$kid])"; 
     $result_c= $wpdb->get_var("SELECT meta_value FROM wp_frm_item_metas WHERE (item_id IN (SELECT count(*) as c,id FROM wp_frm_items WHERE form_id ='$kid' && user_id='". (int)$user_ID ."') && field_id=$ff_id_c[$kid]) ORDER BY c DESC"); 
     echo $result_c; 
    } 
} 
+0

無論你正在嘗試做的,你的邏輯不工作:你不能這樣做'WHERE ITEM_ID =(SELECT COUNT(*)爲C,ID)'...您選擇兩列( count&id),並說他們應該等於一列(item_id)。 – Konerak 2012-02-20 07:55:29

+0

你可以顯示示例數據嗎? – shahkalpesh 2012-02-20 08:00:55

回答

5

嘗試IN子句

SELECT meta_value FROM wp_frm_item_metas 
WHERE (item_id IN (
        SELECT id FROM 
        wp_frm_items WHERE 
        form_id ='9' && user_id='1' 
        ) 
     && field_id=128 
     ) 
1

嘗試

WHERE item_id IN (<your sub query>)而不是WHERE item_id=

1

我看你要加入兩個表。你爲什麼不以通常的方式來做呢? :)

select meta_value from wp_frm_item_metas metas 
join wp_frm_items items on 
items.id = metas.item_id 
where items.form_id = 9 and items.user_id = 1 and metas.field_id = 128