连接两个表后打印标题和计数ID的SQL语句
Posted
技术标签:
【中文标题】连接两个表后打印标题和计数ID的SQL语句【英文标题】:SQL statement for printing title and count ID after joining two table 【发布时间】:2013-01-10 03:36:51 【问题描述】:SELECT b.post_title
, a.post_id
, Deriv1.Count
FROM wp_posts b
, wp_postmeta a
LEFT OUTER JOIN (
SELECT meta_value, COUNT( * ) AS Count
FROM wp_postmeta
GROUP BY meta_value
) Deriv1
ON a.post_id = Deriv1.meta_value
WHERE a.meta_value = 1
AND a.meta_key = 'type-select'
AND b.post_status = 'publish'
and post_type = 'car-cc'
SQl STATEMENT
的当前问题是,当我提供 meta_value =1
时,它正在获取所有值,即 post_id
,其中没有 meta_value =1
也被列出。
http://sqlfiddle.com/#!2/1115a7/1
【问题讨论】:
你有一个产品加入;表wp_post
和wp_postmeta
是如何关联的?
【参考方案1】:
我认为问题在于您没有加入 wp_posts 表和 wp_postmeta 表。将此添加到您的 WHERE 子句中:
AND a.post_id = b.ID
或者,只需在两个表上执行 INNER JOIN:
SELECT b.post_title
, a.post_id
, Deriv1.Count
FROM wp_posts b INNER JOIN
wp_postmeta a ON a.post_id = b.ID
LEFT OUTER JOIN (
SELECT meta_value, COUNT( * ) AS Count
FROM wp_postmeta
GROUP BY meta_value
) Deriv1
ON a.post_id = Deriv1.meta_value
WHERE a.meta_value = 1
AND a.meta_key = 'type-select'
AND b.post_status = 'publish'
and post_type = 'car-cc'
顺便说一句——你想要每个组的计数吗?如果是这样,您的查询可以简化:
SELECT b.post_title, a.post_id, COUNT( * ) as Total
FROM wp_posts b INNER JOIN
wp_postmeta a ON a.post_id = b.ID
WHERE a.meta_value = 1
AND a.meta_key = 'type-select'
AND b.post_status = 'publish'
and post_type = 'car-cc'
GROUP BY b.post_title, a.post_id
这里有一些更新的fiddle。不确定您想要的输出。
祝你好运。
【讨论】:
认为你是一个 SQL 极客。 @sgeddes以上是关于连接两个表后打印标题和计数ID的SQL语句的主要内容,如果未能解决你的问题,请参考以下文章