将多个SQL查询组合在一起具有限制

时间:2018-04-02 06:41:25

标签: mysql sql join mysqli

这是我的表

DB -Fiddle Link还有 SQL FIDDLE LINK

`id`, `pname`, `comapny_id`, `premium`
(1, 'aaaa', 1, '1'),
(2, 'bbbb', 1, '2'),
(3, 'cccc', 1, '3'),
(4, 'dddd', 1, '2'),
(5, 'eeee', 1, '1'),
(6, 'ffff', 1, '3'),
(7, 'gggg', 1, '3'),
(8, 'hhhh', 1, '2'),
(9, 'iiii', 1, '1'),
(10, 'jjjj', 1, '2');

我想结合3个查询。

我试过

SELECT *
FROM query_test 
WHERE company_id = 1 AND premium = 1 
LIMIT 3 
INNER JOIN query_test ON SELECT * FROM query_test WHERE company_id = 1 AND premium = 2 LIMIT 4;

但这对我不起作用。如何使用SQL join加入以下三个查询?我正在学习W3Schools的SQL加入。

查询#1:

SELECT * 
FROM query_test 
WHERE company_id = 1 AND premium = 1 
LIMIT 3

查询#2:

SELECT * 
FROM query_test 
WHERE company_id = 1 AND premium = 2 
LIMIT 4

查询#3:

SELECT * 
FROM query_test 
WHERE company_id = 1 AND premium = 3 
LIMIT 3

如何以最少的时间消耗实现这一目标?

应该感谢帮助。

Gracias de antemano。

4 个答案:

答案 0 :(得分:4)

尝试将LIMITUNION一起使用,并使用正确的语法:

(SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 1 LIMIT 3)
UNION ALL
(SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 2 LIMIT 4)
UNION ALL
(SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 3 LIMIT 3);

答案 1 :(得分:1)

您可以使用UNION

  

UNION用于将多个SELECT语句的结果合并到一个结果集中。

SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 1 LIMIT 3
UNION
SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 2 LIMIT 4
UNION
SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 3 LIMIT 3;

答案 2 :(得分:1)

最快的方法是使用UNION

    SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 1 LIMIT 3
    UNION
    SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 2 LIMIT 4
    UNION
    SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 3 LIMIT 3

答案 3 :(得分:0)

试试这个

SELECT * FROM 
    (SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 1 LIMIT 2) AS G 
UNION ALL 
    (SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 2 LIMIT 2) 
UNION ALL 
    (SELECT * FROM query_test WHERE comapny_id = 1 AND premium = 3 LIMIT 2)

它的工作和测试。!