3
如果我想要得到一個布爾值1,如果id在一個表中,如果不是0,最好/最快的方式是什麼?多個存在vs聯盟
答:2存在具有OR
SELECT
EXISTS(SELECT 1 FROM a WHERE id = 1)
OR EXISTS(SELECT 1 FROM b WHERE id = 1)
B:1 UNION已存在
SELECT EXISTS(
SELECT 1 FROM a WHERE id = 1
UNION
SELECT 1 FROM b WHERE id = 1)
C:聯盟與限制
SELECT 1 FROM a WHERE id = 1
UNION
SELECT 1 FROM b WHERE id = 1
UNION
SELECT 0
LIMIT 1
如果你有一個更好的方式,然後我3解決方案,請寫下來。
描述:
答:
+------+-------------+-------+-------+---------------+---------+---------+-------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+-------------+-------+-------+---------------+---------+---------+-------+------+----------------+
| 1 | PRIMARY | NULL | NULL | NULL | NULL | NULL | NULL | NULL | No tables used |
| 3 | SUBQUERY | a | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index |
| 2 | SUBQUERY | b | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index |
+------+-------------+-------+-------+---------------+---------+---------+-------+------+----------------+
B:
+------+--------------+------------+-------+---------------+---------+---------+-------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+--------------+------------+-------+---------------+---------+---------+-------+------+----------------+
| 1 | PRIMARY | NULL | NULL | NULL | NULL | NULL | NULL | NULL | No tables used |
| 2 | SUBQUERY | a | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index |
| 3 | UNION | b | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index |
| NULL | UNION RESULT | <union2,3> | ALL | NULL | NULL | NULL | NULL | NULL | |
+------+--------------+------------+-------+---------------+---------+---------+-------+------+----------------+
C:
+------+--------------+--------------+-------+---------------+---------+---------+-------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+--------------+--------------+-------+---------------+---------+---------+-------+------+----------------+
| 1 | PRIMARY | a | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index |
| 2 | UNION | b | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index |
| 3 | UNION | NULL | NULL | NULL | NULL | NULL | NULL | NULL | No tables used |
| NULL | UNION RESULT | <union1,2,3> | ALL | NULL | NULL | NULL | NULL | NULL | |
+------+--------------+--------------+-------+---------------+---------+---------+-------+------+----------------+
「使用連接緩衝區」聽起來很貴 –