[英]Bind multiple queries into one result
Can anybody help me to get a result form multiple SQL requests: 谁能帮我从多个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
I just want to find out how many custom posts in my WP MySQL by sending one SQL requests. 我只想通过发送一个SQL请求找出我的WP MySQL中有多少个自定义帖子。
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) 使用UNION ALL组合查询(它们需要具有相同数量的列)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.