简体   繁体   中英

Bind multiple queries into one result

Can anybody help me to get a result form multiple SQL requests:

SELECT *
(COUNT(*) AS Records FROM wp_posts WHERE post_type='news' AND post_status='publish') as News,
(COUNT(*) AS Records FROM wp_posts WHERE post_type='promotion' AND post_status='publish') as Promos,
(COUNT(*) AS Records FROM wp_posts WHERE post_type='contact' AND post_status='publish') as Contacts
FROM wp_posts

I just want to find out how many custom posts in my WP MySQL by sending one SQL requests.

There is no need for subqueries at all:

SELECT 
  SUM(CASE WHEN post_type='news' THEN 1 ELSE 0 END) AS News,
  SUM(CASE WHEN post_type='promotion' THEN 1 ELSE 0 END) AS Promos,
  SUM(CASE WHEN post_type='contact' THEN 1 ELSE 0 END) AS Contacts
FROM wp_posts
WHERE post_status='publish';

or even shorter:

SELECT 
  SUM(IF(post_type='news', 1, 0)) AS News,
  SUM(IF(post_type='promotion', 1, 0)) AS Promos,
  SUM(IF(post_type='contact', 1, 0)) AS Contacts
FROM wp_posts
WHERE post_status='publish';

Use UNION ALL to combine the queries (they need to have the same number of columns)

SELECT * FROM (
SELECT 1
UNION ALL 
SELECT 2
)

You can issue one select with three nested select queries and get the results as columns:

SELECT
(SELECT COUNT(*) FROM wp_posts WHERE post_type='news' AND post_status='publish') as News,
(SELECT COUNT(*) FROM wp_posts WHERE post_type='promotion' AND post_status='publish') as Promos,
(SELECT COUNT(*) FROM wp_posts WHERE post_type='contact' AND post_status='publish') as Contacts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM