sqlite 使用UNION将两个语句与LIMITS组合在一起

42fyovps  于 2022-11-24  发布在  SQLite
关注(0)|答案(4)|浏览(217)

是否有办法将这两个语句合并为一个语句而不产生重复条目?

SELECT * FROM Seq where JULIANDAY('2012-05-25 19:02:00')<=JULIANDAY(TimeP) 
         order by TimeP limit 50

SELECT * FROM Seq where JULIANDAY('2012-05-29 06:20:50')<=JULIANDAY(TimeI)  
         order by TimeI limit 50

SQLITE不支持我的第一个明显的尝试(语法错误:Limit子句应该在UNION之后,而不是之前):

SELECT * FROM Seq where JULIANDAY('2012-05-25 19:02:00')<=JULIANDAY(TimeP) 
         order by TimeP limit 50
UNION
SELECT * FROM Seq where JULIANDAY('2012-05-29 06:20:50')<=JULIANDAY(TimeI)
         order by TimeI limit 50
6kkfgxo0

6kkfgxo01#

使用子查询并在其中执行限制。

SELECT  *
FROM    (   SELECT  * 
            FROM    Seq 
            WHERE   JULIANDAY('2012-05-25 19:02:00') <= JULIANDAY(TimeP) 
            ORDER BY TimeP
            LIMIT 50
        )
UNION
SELECT  *
FROM    (   SELECT  * 
            FROM    Seq 
            WHERE   JULIANDAY('2012-05-29 06:20:50') <= JULIANDAY(TimeI) 
            ORDER BY TimeI
            LIMIT 50
        )
cunj1qz1

cunj1qz12#

查询分阶段处理:

  1. FROM子句和所有连接;
  2. WHERE子句和所有 predicate 。因此,如果您希望在结果集中看到NULL值,您永远不应该在WHERE节中过滤OUTER连接的表列,因为这会将您的查询转换为INNER连接;
  3. GROUP BYHAVING条款;
    1.查询组合:UNIONINTERSECTEXCEPTMINUS
  4. ORDER BY
  5. LIMIT
    因此,正如其他人所指出的,在 * UNION子句之前使用ORDER BYLIMIT * 在语法上是错误的,应该使用子查询:
SELECT *
  FROM (SELECT * FROM Seq
         WHERE JULIANDAY('2012-05-25 19:02:00') <= JULIANDAY(TimeP) 
         ORDER BY TimeP LIMIT 50) AS tab1
UNION
SELECT *
  FROM (SELECT * FROM Seq
         WHERE JULIANDAY('2012-05-29 06:20:50') <= JULIANDAY(TimeI)  
         ORDER BY TimeI LIMIT 50) AS tab2;
np8igboo

np8igboo3#

SELECT * from
    (SELECT *
    FROM Seq
    where JULIANDAY('2012-05-25 19:02:00')<=JULIANDAY(TimeP)
    order by TimeP limit 50)
UNION
SELECT * from
    (SELECT *
    FROM Seq
    where JULIANDAY('2012-05-29 06:20:50')<=JULIANDAY(TimeI)
    order by TimeI limit 50)
ar5n3qh5

ar5n3qh54#

我有一个表buysell_product。我想根据views_1列选择前5个,并使用views_2列选择另一个前5个,然后合并这两个表。两个查询中的列是相同的。期望这样做能起作用,但它没有:

SELECT id, name, views_1, views_2
    FROM buysell_product
    ORDER BY views_1 DESC
    LIMIT 5
UNION
SELECT id, name, views, views_2
    FROM buysell_product as b
    ORDER BY views_2 DESC
    LIMIT 5

错误:

Execution finished with errors.
Result: ORDER BY clause should come after UNION not before
At line 1:
...

它们分别工作,但我需要合并它们:

SELECT * FROM (
    SELECT id, views_1, views_2, name
    FROM buysell_product
    ORDER BY views_1 DESC
    LIMIT 5
)
UNION
SELECT * FROM (
    SELECT id, views_1, views_2, name
    FROM buysell_product as b
    ORDER BY views_2 DESC
    LIMIT 5
)

结果:
| 标识符|视图_1|视图_2|姓名|
| - -|- -|- -|- -|
| 2个|四十一|十六|优秀的2013款福特生态运动|
| 三个|七十二|10个|卓越的现代creta|
| 五个|三十九|三十九|iPhone 11 128GB|
| 七个|十二|八十四|卓越的现代creta sx|
| 九个|三十七|八十四|大众波罗1.2 GT AMT 2017款|
| 四十四|三十四|八十一|Usupso按摩防滑拖鞋|
| 四十五|十五|七十五|大蒜粉-100 Gm|
| 五十七|三十五|十一|iPhone 13和14|
| 六十七|十五|七十三|通用触摸屏电容式手写笔|

相关问题