2015-11-11 90 views
0

我有一個問題,在同一查詢中向不同的表獲取4個SQL請求。查詢是:將小查詢合併爲一個較大的mysql查詢

SELECT COUNT(*) AS posts FROM `wp_posts` WHERE post_type='updates' AND post_status='publish' 

而且

SELECT COUNT(*) AS posts FROM `wp_posts` WHERE post_type='post' AND post_status='publish' 

wp_posts表結構是:

| ID | title | post_type | post_status | 
------------------------------------------------ 
| 1 | Name | updates | publish | 
| 2 | Name 2 |  post | publish | 

其他請求:

SELECT COUNT(*) AS users FROM wp_usermeta WHERE wp_usermeta.meta_value LIKE '%delegate%' 

wp_usermeta的表結構我S:

| ID | user_id | meta_key  |   meta_value   | 
----------------------------------------------------------------- 
| 29 | 4 | ei_capabilities | a:1:{s:13:"delegate";b:1;} | 

,最後一個:

SELECT wp_postmeta.meta_value AS version FROM wp_postmeta WHERE wp_postmeta.meta_key='content_version' AND post_id=1 

wp_postmeta表結構是:

| ID | post_id | title | meta_key  | meta_value | 
--------------------------------------------------------------- 
| 21 |  1  | Name | content_version |  1  | 

有沒有辦法將它們組合成一個要求嗎?

+0

一個rwquest手段?作爲一個查詢? –

+0

嗨@SubinCPoonamgode是隻是在一個SELECT – qqruza

+0

pls添加表結構,或者我們可以加入這兩個表之間的字段(如果存在的話) – user3600910

回答

1

首先兩個查詢是相似的,所以我做了wp_posts爲主要table.The其餘兩個查詢的子查詢。

SELECT 
    (SUM(CASE WHEN post_type='updates' AND THEN 1 ELSE 0 END)) as col1, 
    (SUM(CASE WHEN post_type='post' AND post_type='post' THEN 1 ELSE 0 END)) as col2, 
    (SELECT COUNT(*) AS users FROM wp_usermeta WHERE wp_usermeta.meta_value LIKE '%delegate%') AS col3, 
    (SELECT wp_postmeta.meta_value AS version FROM wp_postmeta WHERE wp_postmeta.meta_key='content_version' AND post_id=1 LIMIT 1) as col4 
    FROM 
    wp_posts 
    WHERE post_status='publish' 

希望這有助於

+0

謝謝@SubinCPoonamgode。我在你的例子中發現了一些錯誤,修正了它們,它似乎工作正常。 – qqruza

1

試試這個

select(
    select 
    sum(case when post_type='updates' AND post_status='publish' then 1 else 0 end) from wp_posts) as '1Query', 
    (select 
sum(case when post_type='post' AND post_status='publish' then 1 else 0 end) as '2Query' 
    from wp_posts), 
    (select 
    SUM(CASE WHEN wp_usermeta.meta_value LIKE '%delegate%' THEN 1 ELSE 0 END) AS users 
    FROM wp_usermeta) as Users, 
    (
    SELECT wp_postmeta.meta_value AS version FROM wp_postmeta WHERE wp_postmeta.meta_key='content_version' AND post_id=1)as Version 
+0

Hi @ user3600910我有一個錯誤#1064 - 你的SQL語法錯誤; – qqruza

+0

好吧,現在試試吧,語法有問題 – user3600910

+0

另一個錯誤 - #1241 - 操作數應該包含1列 – qqruza