将多个查询绑定到一个结果中

时间:2015-09-25 10:16:44

标签: mysql sql

任何人都可以帮我从多个SQL请求中获取结果:

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

我只想通过发送一个SQL请求来查找WP MySQL中有多少个自定义帖子。

3 个答案:

答案 0 :(得分:4)

根本不需要子查询:

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';

甚至更短:

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';

答案 1 :(得分:1)

使用 UNION ALL 组合查询(它们需要具有相同数量的列)

SELECT * FROM (
SELECT 1
UNION ALL 
SELECT 2
)

答案 2 :(得分:1)

您可以使用三个嵌套的选择查询发出一个选择,并将结果作为列:

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