2017-05-16 89 views
0

我有兩個表格,我想要獲取所有(後)記錄,其中的語言是英語,捐款金額高於25歐元。MySQL查詢;選擇加入的多個數據的數據

這是查詢構造;

SELECT wp_posts.* , wp_postmeta.* 
FROM wp_posts 
JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id 
WHERE (wp_postmeta.meta_key = 'lang_code' AND wp_postmeta.meta_value = 'en') 
AND (wp_postmeta.meta_key = 'donated' AND CAST(wp_postmeta.meta_value AS SIGNED) > '25') 
AND wp_posts.post_type = 'donation' 
AND wp_posts.post_status = 'publish' 
ORDER BY wp_posts.post_date DESC 
LIMIT 1 OFFSET 0; 

表#1(wp_posts)

--------------------------------------------------- 
ID | name   | post_type | post_status 
--------------------------------------------------- 
01 | test entry 1 | donation | publish 
02 | test entry 2 | donation | publish 
03 | test entry 3 | donation | awaiting 

表#2(wp_postmeta);

--------------------------------------------------- 
meta_id | post_id | meta_key | meta_value 
--------------------------------------------------- 
23  | 01  | lang_code | en 
84  | 01  | donated | 3100 
25  | 02  | lang_code | en 
63  | 02  | donated | 15 

該演示數據的預期結果;

--------------------------------------------------- 
ID | name   | post_type | post_status 
--------------------------------------------------- 
01 | test entry 1 | donation | publish 

我怎樣才能得到我需要的結果,沒有子查詢?

+1

我沒有看到捐款數額的任何列。 –

+0

@TimBiegeleisen它是meta_key'donated'和meta_value列匹配數據的組合。 @OP:你爲什麼不想使用子查詢?你的SQL是否工作(看起來可能)。如果有效:它的問題在哪裏? – daZza

+0

@daZza子查詢不會使查詢真的很慢嗎?我也認爲這個查詢是可以的。但它不能過濾多個元/鍵=>元/值。 – Daan

回答

0

爲此,您可以使用兩個連接:

SELECT p.* , pml.*, pmd.* -- although you probably only want the value column 
FROM wp_posts p JOIN 
    wp_postmeta pml 
    ON p.ID = pml.post_id AND 
     pml.meta_key = 'lang_code' AND 
     pml.meta_value = 'en' JOIN 
    wp_postmeta pmd 
    ON p.ID = pmd.post_id AND 
     pmd.meta_key = 'donated' AND CAST(pmd.meta_value AS SIGNED) > 25 WHERE p.post_type = 'donation' AND p.post_status = 'publish' 
ORDER BY p.post_date DESC 
LIMIT 1 OFFSET 0; 
+0

太棒了,像魅力一樣工作! (我得到1錯誤開wp_posts.ID需要p.ID) – Daan