如何在两个表上进行选择,然后将它们连接到mySQL中

时间:2017-12-28 00:20:14

标签: mysql r database dplyr

我有两个表,A和B.表A有两列,&#34; ID&#34;和&#34; age&#34;。表B有两列,&#34; ID&#34;和&#34;等级&#34;。我想选择年龄> 25的A行,B中等级<90的行,然后将结果加在一起。

在R中,这可以通过代码来实现:

0x7670

如何在mySQL中做同样的事情?更具体地说,mySQL中有一种方法可以将查询结果存储到新变量(如sub_A和sub_B)中,然后将sub_A和sub_B连接在一起吗?

我尝试使用&#34; CREATE TEMPORARY TABLE&#34;但我没有权限在数据库中创建临时表。

2 个答案:

答案 0 :(得分:2)

可以连接两个子查询:

select *
from (
    select *
    from table_a 
    where age > 25
) sub_a
inner join (
    select *
    from table_b
    where grade < 90
) sub_b using(ID)

但没有必要这样做。您可以加入两个表(在ID上)并在同一个WHERE子句中过滤数据:

select *
from table_a a
join table_b b using(ID)
where a.age   > 25
  and b.grade < 90

答案 1 :(得分:0)

OP已使用dplyr来展示他希望使用mySQL实现的预期结果。

为了完整起见并且因为data.table的语法是similar to SQL,我想说明如何使用data.table以两种方式实现OP的要求:

library(data.table)

# filter/select before merge
merge(setDT(A)[age > 25], setDT(B)[Grade < 90])

# filter/select after  merge
merge(setDT(A), setDT(B))[age > 25 & Grade < 90]

两个语句都返回相同的结果:

   ID age Grade
1:  6  26    86
2:  7  27    87
3:  8  28    88
4:  9  29    89
相关问题