I have these four tables described bellow. Basically I have feeds with entries relationed with categories, and each category can be a main category or not (flag named as "principal"). Also each feed can be a partner feed or not (flag named as "parceiro").
I want to select all feed entries from partrners feeds, so I have this:
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
Now I need to include in this result all entries from no partners feeds that are in main categories, I mean, only entries in main categories. So, the query bellow do this:
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
I need to merge these results in one query with limit 5 ordened by date.
Is UNION the best solution, if so, how to write the query?
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)
)