Min*_*esh 6 mysql sql union join
让我们说我有2个结果集如下
R1 R2
| 1 | | 5 |
| 2 | | 6 |
| 3 | | 7 |
| 4 | | 8 |
Run Code Online (Sandbox Code Playgroud)
我需要将这些结果合并到一个SET中,所以我有这样的事情:
R3
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
Run Code Online (Sandbox Code Playgroud)
目前,我正在使用UNION这样做:
SELECT c_1 AS result FROM table WHERE c_1=3 OR c_2=3
UNION
SELECT c_2 AS result FROM table WHERE c_1=3 OR c_2=3
Run Code Online (Sandbox Code Playgroud)
基本上,我最终在表上执行两次相同的操作,每次只检索不同的行.有没有更有效的方法可以做到这一点?我需要将结果放在一个列中,因为这是IN的限制.从长远来看,我需要做的就是这个
SELECT name FROM person WHERE person_id IN
(SELECT c_1 AS result FROM table WHERE c_1=3 OR c_2=3
UNION
SELECT c_2 AS result FROM table WHERE c_1=3 OR c_2=3)
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法去寻找所有这些?欢迎任何和所有帮助.
取而代之的是的IN ()子查询,你可以执行INNER JOIN上无论是 c_1 OR c_2
SELECT
name
FROM
person
/* Join against the other table on *either* column c_1 or c_2 */
INNER JOIN `table` ON `table`.c_1 = person.person_id OR `table`.c_2 = person.person_id
WHERE
/* And the WHERE condition only needs to be applied once */
c_1 = 3 OR c_2 = 3
Run Code Online (Sandbox Code Playgroud)
http://sqlfiddle.com/#!2/4d159/1