查询来自共享相同LIMIT的多个表

时间:2015-03-23 16:15:20

标签: php mysql sql subquery

我有一个共同的分页限制,每页显示30个元素

现在我需要使用来自3个不同表的匹配来获得结果,并从每个表中获取3个字段。

表格字段 news_id,标题,内容 表B字段 events_id,标题,内容 表C字段 enc_id,标题,内容

以及条件

WHERE ( MATCH (title) AGAINST('{$search}') OR MATCH(content) AGAINST('{$search}')OR MATCH(resume) AGAINST('{$search}') )

此外,每个表行都有一个状态字段,在where条件中必须等于1。

最后,我需要为全局查询执行LIMIT $start_from, 30

任何可行的方法吗?

**编辑**

这是我用于一个表的查询

"SELECT
    news_id,title,
    FROM news
    WHERE ( MATCH (title) AGAINST('{$search}') OR MATCH(resume)      AGAINST('{$search}')OR MATCH(content) AGAINST('{$search}') 

  AND noticias.status = 1 

    LIMIT 0, 30"

这就是我尝试过但没有成功的事情。它应该带7行,但带来30个而不是

SELECT
news.news_id AS id,
events.events_id AS id,
enc.enc_id AS id,
news.title AS title,
events.title AS title,
enc.title AS title  

FROM news, events, enc

WHERE ( MATCH (news.title) AGAINST('{$search}') OR MATCH(news.resume) AGAINST('{$search}')OR MATCH(news.content) AGAINST('{$search}') 
OR  MATCH (enc.title) AGAINST('{$search}') OR MATCH(enc.resume) AGAINST('{$search}')OR MATCH(enc.content) AGAINST('{$search}')  
OR MATCH (events.title) AGAINST('{$search}') OR MATCH(events.resume) AGAINST('{$search}')OR MATCH(events.content) AGAINST('{$search}') ) 

AND ( news.status = 1 OR enc.status = 1 OR events.status = 1)

LIMIT 0, 30

1 个答案:

答案 0 :(得分:2)

我找到了一个解决方案,所以我会在这里分享,以防其他人需要它。

使用UNION

(SELECT news_id AS id, title, 'news' AS origin FROM news WHERE ( MATCH (title) AGAINST('{$search}') OR MATCH(resume) AGAINST('{$search}')OR MATCH(content) AGAINST('{$search}') AND status = 1) )
UNION
(SELECT events_id AS id, title, 'events' AS origin FROM events WHERE ( MATCH (title) AGAINST('{$search}') OR MATCH(resume) AGAINST('{$search}')OR MATCH(content) AGAINST('{$search}') AND status = 1) )
UNION
(SELECT enc_id AS id, title, 'enc' AS origin FROM enc WHERE ( MATCH (title) AGAINST('{$search}') OR MATCH(resume) AGAINST('{$search}')OR MATCH(content) AGAINST('{$search}') AND status = 1) )
LIMIT $start_from, 30

我使用字段origin来了解每个内容来自哪个表格。