子查询返回多行

时间:2012-02-20 07:50:35

标签: php mysql sql

所有

我有两张桌子 enter image description here

第一张表是: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列

我的代码是

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; 
    }
}

3 个答案:

答案 0 :(得分: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 :(得分:1)

尝试

WHERE item_id IN (<your sub query>)代替WHERE item_id=

答案 2 :(得分: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