简体   繁体   中英

Change SQL from having or/and in one query to union

I have the following SQL:

SELECT * FROM table t WHERE (t.active = 1 OR t.something = 0) AND t.else = 0 LIMIT 5000;

I can't use any index on this query, so I want to change it into:

SELECT *
FROM table t WHERE t.active = 1 AND t.else = 0 LIMIT 5000
UNION
SELECT *
FROM table t WHERE t.something = 0 AND t.else = 0 LIMIT 5000;

Will these SQLs give the the same results? What will happen when two SQLs from UNION will give me the same row?

You have a couple of issues there.

You queries use limit (although you probably should put brackets around each individual unioned query). None have an order so using a limit does not make much sense (as you do not control which 5000 records are returned). The difference here is that your first query can return up to 5000 rows and you 2nd query the one using UNION) can return up to 10000 rows.

The 2nd issue is if you have non unique rows (not likely when using SELECT *, but you shouldn't use SELECT * in live situations). If you have 2 identical rows the first query would return them both, while the 2nd would only return one of them. Note that you could bypass this using UNION ALL, but that could potentially give you a different problem, as a row that satisfied both the first and second unioned queries would be returned twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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