简体   繁体   English

从两个不同的SQL表返回结果作为搜索结果

[英]Returning results from two different SQL tables as search results

I have two different tables containing similar data but slightly different format. 我有两个包含相似数据但格式略有不同的不同表。

Is it possible to return search results from both tables? 是否可以从两个表中返回搜索结果? I also need to paginate these results. 我还需要对这些结果进行分页。

You can use UNION to query both tables and return results in just one query: 您可以使用UNION来查询两个表并仅通过一个查询返回结果:

SELECT field1,field2  FROM table1
UNION
SELECT field1,field2 FROM table2

If table1 and table2 are very different you can combine the UNION with a more complex FROM using another select something like ... 如果table1table2截然不同,则可以将UNION与更复杂的FROM使用,例如使用另一个select

SELECT field1,field2  FROM (SELECT id1 as field1,id2 as field2 FROM table1a,table1b WHERE id1 = id2)
UNION
SELECT field1,field2 FROM table2

To paginate results you can enclose a union in another select and use limit and offset .... 要对结果进行分页,可以将并集括在另一个select并使用limitoffset ...。

SELECT field1,field2 FROM (
    SELECT field1,field2  FROM table1
    UNION
    SELECT field1,field2 FROM table2
) LIMIT 100 OFFSET 0

If you give us a small description of the tables structure we might be able to help better. 如果您对表结构进行简单描述,我们可能会更好地提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM