选择查询确定但不作为视图查询

时间:2017-05-06 07:33:19

标签: mysql view

我有一个查询,它提供了正确的结果作为选择查询,但当我将其用作视图时,它创建视图但浏览视图会出现错误“子查询返回超过1行”。该查询采用“my_postmeta_table”表上的“meta_key”字段,并使其成为当前行的“meta_value”字段的列名。它是这样的:

这是表格中的格式:

post_id  meta_key  meta_value
1        key1      val1
1        key2      val2   
2        key1      val3
2        key2      val4  

select查询返回如下所示的resault:

post_id  key1  key2
1        val1  val2
2        val3  val4

这是查询:

create or REPLACE view contacts2 as select
    post_id pid, 
    post_date Date, 
    (SELECT  meta_value from my_postmeta_table where meta_key="contact_country" and post_id=pid)  AS "Country", 
    (SELECT  meta_value from my_postmeta_table where meta_key="contact_usa_states" and post_id=pid)  AS "USA State",  
    (SELECT  meta_value from my_postmeta_table where meta_key="contact_subject" and post_id=pid)  AS "Subject",  
    (SELECT meta_value from my_postmeta_table where meta_key="contact_first_name"  and post_id=pid)  AS "First Name",  
    (SELECT meta_value from my_postmeta_table where meta_key="contact_last_name"  and post_id=pid)  AS "Last Name",  
    (SELECT meta_value from my_postmeta_table where meta_key="contact_company"  and post_id=pid)  AS "Company",  
    (SELECT meta_value from my_postmeta_table where meta_key="contact_position"  and post_id=pid)  AS "Position",  
    (SELECT meta_value from my_postmeta_table where meta_key="contact_email"  and post_id=pid)  AS "Email",  
    (SELECT meta_value from my_postmeta_table where meta_key="contact_message"  and post_id=pid)  AS "Message" 
    from my_postmeta_table, my_posts_table where my_posts_table.ID=my_postmeta_table.post_id and my_posts_table.post_type="contact"  GROUP by post_id;

所以...如果我从上面的代码中省略了“创建或替换视图contacts2 as”,那么就会有很好的解决方法。

谢谢

1 个答案:

答案 0 :(得分:0)

如果您希望所有子查询只返回1条记录,则只需将limit 1添加到每个子查询的末尾。这样mysql就会知道子查询肯定只返回1条记录。