获得2个表的结果,总共10个限制

时间:2014-03-27 03:22:56

标签: php sql select union

我需要从2个表中得到结果,限制总数为10


例如1:
如果我table_1和table_2有15条记录,我的结果将是20:

SELECT * FROM table_1 limit 10 
UNION ALL 
SELECT * FROM table_2 limit 10 


例如2:
table_1如果我有3条记录并记录table_2 20,我的结果将是8:

SELECT * FROM table_1 limit 5
UNION ALL 
SELECT * FROM table_2 limit 5



需要在限制为10的选择中包含SELECT ... UNION ALL SELECT ...' 类似的东西:

select * from 
(Select * FROM tbl_1) T1, 
UNION ALL 
(Select * FROM tbl_2) T2, 
limit 10

这个例子不起作用,只是为了举例说明我需要如何获得查询 是一个真实的案例...有人能伸出援手吗?
谢谢

2 个答案:

答案 0 :(得分:1)

使用联合时,最好单独选择列以确保它们在查询之间匹配。在第一个查询上设置列别名也是值得的,这样您就可以在查询的其他部分中唯一地引用它们。

我修改了这个答案,以证明使用'排序键'为每个单独的查询选择,然后由控制显示哪些列的外部查询应用。它们的显示顺序是什么。

我还提供了一个 SQLFiddle... ,您可以用它来播放'用它。

测试示例:

SELECT report.title 
FROM 
(SELECT title AS title,
       'Q01'  AS query_identifier, 
       id     AS sort_key_01,        
        0     AS sort_key_02 
FROM parents
UNION 
SELECT child_text,
       'Q02',  
        parent_id, 
        id  FROM children
) report
ORDER BY 
         report.query_identifier, 
         report.sort_key_01, 
         report.sort_key_02

结果:

first parent title
second parent title
third parent title
first parent first child
first parent second child
second parent first child
second parent second child
third parent first child
third parent second child
third parent third child

答案 1 :(得分:0)

应该如下:

(SELECT * FROM table_1)
UNION ALL 
(SELECT * FROM table_2)
LIMIT 10 

使用ORDER BY或LIMIT子句对整个UNION结果进行排序或限制,括号各个SELECT语句并将ORDER BY或LIMIT放在最后一个之后。