Warm tip: This article is reproduced from serverfault.com, please click

SQL query in python

发布于 2020-11-29 14:14:48

I have a test table with 2000 rows and I am trying to select only from the first 1000 rows those rows where xxx = 0.

I tried with:

mydb.cursor().execute("SELECT column_N FROM test_table LIMIT 1000 WHERE xxx = 0")

but this returns an error.

Note: I wish to get the rows containing the argument from within the first 1000 rows and not the first 1000 rows containing the argument.

Questioner
Nocciolate
Viewed
0
Lukasz Szozda 2020-11-29 22:28:35

WHERE clause needs to be placed before LIMIT:

SELECT column_N 
FROM test_table 
WHERE xxx = 0
-- ORDER BY col_name  -- to have stable resultset, ORDER BY is needed
LIMIT 1000 

EDIT:

SELECT s.column_N
FROM (
    SELECT *
    FROM test_table 
    ORDER BY col_name  -- to have stable first 1000 rows, ORDER BY is needed
    LIMIT 1000) s
WHERE s.xxx = 0;

Tables are unordered sets, so LIMIT 1000 may vary betweens runs, that is why ORDER BY was added.