哪个是执行此查询的最佳方法?也许是UNION

时间:2010-08-30 20:11:19

标签: sql mysql union

我在下面描述了这四个表格。基本上我有与类别相关的条目的提要,并且每个类别可以是主要类别或不是(标记为“主要”)。 此外,每个Feed都可以是合作伙伴Feed(标记为“parceiro”)。

我想从partrners Feed中选择所有Feed条目,所以我有:

SELECT `e` . * , `f`.`titulo` AS `feedTitulo` , `f`.`url` AS `feedUrl`
FROM `feed_entries` AS `e`
INNER JOIN `feeds` AS `f` ON e.feed_id = f.id
INNER JOIN `entries_categorias` AS `ec` ON ec.entry_id = e.id
INNER JOIN `categorias` AS `c` ON ec.categoria_id = c.id
WHERE 
e.deleted =0
AND
f.parceiro =1
GROUP BY `e`.`id`
ORDER BY `e`.`date` DESC
LIMIT 5

现在我需要在此结果中包含来自主要类别中没有合作伙伴供稿的所有条目,我的意思是,只包含主要类别中的条目。所以,查询如下:

SELECT `e` . * , `f`.`titulo` AS `feedTitulo` , `f`.`url` AS `feedUrl`
FROM `feed_entries` AS `e`
INNER JOIN `feeds` AS `f` ON e.feed_id = f.id
INNER JOIN `entries_categorias` AS `ec` ON ec.entry_id = e.id
INNER JOIN `categorias` AS `c` ON ec.categoria_id = c.id
WHERE
e.deleted =0
AND 
c.principal =1
AND 
f.parceiro =0
GROUP BY `e`.`id`
ORDER BY `e`.`date` DESC
LIMIT 5

我需要在一个查询中合并这些结果,其中限制为5或按日期。

UNION是最佳解决方案,如果是,如何编写查询?

CREATE TABLE categorias (
  id int(11) NOT NULL auto_increment,
  nome varchar(100) collate utf8_unicode_ci NOT NULL,
  principal int(1) NOT NULL default '0',
  PRIMARY KEY  (id),
  UNIQUE KEY nome (nome)
)

CREATE TABLE entries_categorias (
  id int(11) NOT NULL auto_increment,
  entry_id int(11) NOT NULL,
  categoria_id int(11) NOT NULL,
  PRIMARY KEY  (id),
  KEY entry_id (entry_id),
  KEY categoria_id (categoria_id)
)

CREATE TABLE feeds (
  id int(11) NOT NULL auto_increment,
  categoria_id int(11) NOT NULL,
  titulo varchar(255) collate utf8_unicode_ci NOT NULL,
  link varchar(255) collate utf8_unicode_ci NOT NULL,
  url varchar(255) collate utf8_unicode_ci NOT NULL,
  parceiro int(1) NOT NULL,
  PRIMARY KEY  (id),
  KEY categoria_id (categoria_id)
)

CREATE TABLE feed_entries (
  id int(11) NOT NULL auto_increment,
  feed_id int(11) NOT NULL COMMENT 'Testando os comentários',
  titulo varchar(255) collate utf8_unicode_ci NOT NULL,
  descricao text collate utf8_unicode_ci NOT NULL,
  slug varchar(255) collate utf8_unicode_ci NOT NULL,
  link varchar(255) collate utf8_unicode_ci NOT NULL,
  permaLink varchar(255) collate utf8_unicode_ci NOT NULL,
  html text collate utf8_unicode_ci NOT NULL,
  `date` datetime NOT NULL,
  created_at datetime NOT NULL,
  deleted int(1) NOT NULL,
  PRIMARY KEY  (id),
  UNIQUE KEY permaLink (permaLink),
  KEY feed_id (feed_id)
)

1 个答案:

答案 0 :(得分:2)

您应该做的就是更改查询中的WHERE语句:

SELECT `e`.*, `f`.`titulo` as `feedTitulo`, `f`.`url` as `feedUrl`

FROM `feed_entries` as `e`

INNER JOIN `feeds` as `f`
ON e.feed_id = f.id

INNER JOIN `entries_categorias` as `ec`
ON ec.entry_id = e.id

INNER JOIN `categorias` AS `c` 
ON ec.categoria_id=c.id

WHERE (e.deleted = 0 AND f.parceiro = 1) 
OR (e.deleted = 0 AND c.principal=1 AND f.parceiro = 0)

GROUP BY `e`.`id`
ORDER BY `e`.`date` desc
LIMIT 5

新的where语句有两个条件,所以我们只查询一次并检查两个条件,而不是查询同一组表/连接!