正文
正常查询:
MariaDB [test]> select * from test1;
+---------------------------+-------------+
| username | password |
+---------------------------+-------------+
| vampire | mypassword |
| vampire1 | mypassword |
| vampire | random_pass |
+---------------------------+-------------+
3 rows in set (0.000 sec)
使用union查询:
MariaDB [test]> select 1,2 union select * from test1;
+---------------------------+-------------+
| 1 | 2 |
+---------------------------+-------------+
| 1 | 2 |
| vampire | mypassword |
| vampire1 | mypassword |
| vampire | random_pass |
+---------------------------+-------------+
4 rows in set (0.002 sec)
这样查询会得到一个虚拟表,接下来就可以使用这个虚拟表来查找数据:
MariaDB [test]> select `2` from (select 1,2 union select * from test1)a;
+-------------+
| 2 |
+-------------+
| 2 |
| mypassword |
| mypassword |
| random_pass |
+-------------+
4 rows in set (0.001 sec)
当````被过滤时,可以使用别名来解决。
MariaDB [test]> select b from (select 1,2 as b union select * from test1)a;
+-------------+
| b |
+-------------+
| 2 |
| mypassword |
| mypassword |
| random_pass |
+-------------+
4 rows in set (0.031 sec)
拓展
除了直接查数据,还可以通过join
、join...using
来获取列名。
join之后的效果,产生一个虚拟表,并且有重复的列名。
MariaDB [test]> select * from test1 as a join test1 b;
+---------------------------+-------------+---------------------------+-------------+
| username | password | username | password |
+---------------------------+-------------+---------------------------+-------------+
| vampire | mypassword | vampire | mypassword |
| vampire1 | mypassword | vampire | mypassword |
| vampire | random_pass | vampire | mypassword |
| vampire | mypassword | vampire1 | mypassword |
| vampire1 | mypassword | vampire1 | mypassword |
| vampire | random_pass | vampire1 | mypassword |
| vampire | mypassword | vampire | random_pass |
| vampire1 | mypassword | vampire | random_pass |
| vampire | random_pass | vampire | random_pass |
+---------------------------+-------------+---------------------------+-------------+
9 rows in set (0.068 sec)
接着使用select 查询:
MariaDB [test]> select * from (select * from test1 as a join test1 b)c;
ERROR 1060 (42S21): Duplicate column name 'username'
可以看到报错,并且把重复的列名显示出来,但是只显示一个,如果要显示另一个则需要使用using,正常using的效果如下:
MariaDB [test]> select * from test1 as a join test1 b using(username);
+---------------------------+-------------+-------------+
| username | password | password |
+---------------------------+-------------+-------------+
| vampire | mypassword | mypassword |
| vampire | random_pass | mypassword |
| vampire1 | mypassword | mypassword |
| vampire | mypassword | random_pass |
| vampire | random_pass | random_pass |
+---------------------------+-------------+-------------+
5 rows in set (0.039 sec)
可以看到重复列username没了,只剩下一个password,那么理所当然的报错只会显示password:
MariaDB [test]> select * from (select * from test1 as a join test1 b using(username))c;
ERROR 1060 (42S21): Duplicate column name 'password'