2017-05-06 36 views
0

我有一個查詢,作爲選擇查詢給出正確的結果,但是當我用它作爲視圖它創建視圖,但瀏覽視圖給出錯誤「子查詢返回多於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 

選擇查詢返回resaults,看起來像這樣:

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」從上面的代碼給出goo d resaults。

謝謝

+1

請參閱https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple- sql-query – Strawberry

+0

嘗試向所有子查詢添加限制1。 – Shadow

+0

1.你不清楚。 「給出正確的結果」是什麼意思?或者「用它作爲一個視圖」?或者「瀏覽視圖」或「好結果」?除了用單詞來解釋你正在做的和已經完成的事情之外,還要按照上面第一條評論的[mcve]解釋情況。 2.閱讀[SELECT with GROUP BY和MySQL的ONLY_FULL_GROUP_BY](https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html)的正確使用方法。如果不在GROUP BY中,或者在GROUP BY列中使用單值,則不要在聚合之外的SELECT中使用列。 – philipxy

回答

0

如果你希望所有的子查詢只返回1的記錄,然後只需添加limit 1到每個子查詢的結束。這樣mysql會知道子查詢只能返回1條記錄。