从数据透视表返回单行

时间:2014-03-08 00:33:31

标签: mysql sql

我有以下三个表

Create table posts (
    post_id Int UNSIGNED NOT NULL AUTO_INCREMENT,
    post_title Varchar(255) NOT NULL,
 Primary Key (post_id)) ENGINE = InnoDB;

Create table publishers (
    publisher_id Int UNSIGNED NOT NULL AUTO_INCREMENT,
    publisher_name Varchar(255) NOT NULL,
 Primary Key (publisher_id)) ENGINE = InnoDB;

Create table publisher_terms (
    term_id Int UNSIGNED NOT NULL AUTO_INCREMENT,
    post_id Int UNSIGNED NOT NULL,
    publisher_id Int UNSIGNED NOT NULL,
 Primary Key (term_id)) ENGINE = InnoDB;

我想只用一个发布商检索所有帖子。我试过跟随内部查询,但我的列错误未知。

select P.post_title FROM posts P, (SELECT PB.publisher_id FROM publisher_terms PB WHERE P.post_id=PB.post_id LIMIT 1) PT;

2 个答案:

答案 0 :(得分:1)

您可以使用此帖子检索发布商的帖子。由于帖子标题不是唯一的,我在结果中包含post_id

select P.post_id, P.post_title, MAX(PS.publisher_name) publisher_name
FROM publisher_terms T
   JOIN posts P
      ON T.post_id = P.post_id
   JOIN publishers PS
      ON T.publisher_id = PS.publisher_id
GROUP BY P.post_id, P.post_title

答案 1 :(得分:1)

这并没有解决潜在的“为什么这不起作用?”但是这可以重新编写为与aggregate_terms上的Count聚合的Join,然后在group by中使用Having子句来限制它吗?

http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html有更明确的说明,但它会是这样的:

SELECT P.post_title, count(publisher_id) as c
  FROM posts P
    JOIN publisher_terms PT
  ON P.post_id = PT.post_id
GROUP BY P.post_title
HAVING c = 1