MySQL查询以使用JOIN从多个表中获取数据

时间:2020-03-05 06:26:37

标签: mysql join

我有两个表需要如下所示的结果。 需要移动,电子邮件和关系在同一行的结果集

有一个具有ID(自动递增)和数据111,112的用户表

i have tried 

select us.id,t1.mobile,t2.email,t1.relation 
from user us
join Table1 t1
on us.id = t1.pid
left join Table2
on t1.pid = t2.pid

doesn't work as expected.
    Table1                                                                    
id(AI)          pid         mobile           relation                                 
 1              111         8080808080       self
 2              111         9090909090       mother
 3              111         2525252525       father
 4              112         1111111111       self
 5              112         2222222222       mother
 6              112         3333333333       father


    Table2                                                                  
id(AI    pid    email             relation                                 
 1       111    abc@xyz.com          self
 2       111    cdf@xyz.com          mother
 3       111    htf@xyz.com          father
 4       112    abc112@xyz.com       self
 5       112    cdf112@xyz.com       mother
 6       112    htf112@xyz.com       father

需要这样的结果:-

 pid            email               mobile           relation                                 
 111         abc@xyz.com          8080808080         self
 111         cdf@xyz.com          9090909090         mother
 111         htf@xyz.com          2525252525         father
 112         abc112@xyz.com       1111111111         self
 112         cdf112@xyz.com       2222222222         mother  
 112         htf112@xyz.com       3333333333         father

3 个答案:

答案 0 :(得分:0)

SELECT t1.pid,t1.mobile,t2.email,t2.relation
FROM `table1` as t1
INNER JOIN table2 as t2 ON t1.pid = t2.pid and t1.relation = t2.relation

答案 1 :(得分:0)

这是您的查询

SELECT t1.pid, t2.email, t1.mobile, t1.relation 
FROM table1 t1 
JOIN table2 t2 on t1.pid=t2.pid and t1.relation=t2.relation

尝试一下以达到预期效果

select us.id,t1.mobile,t2.email,t1.relation 
from user us
join Table1 t1
on us.id = t1.pid
left join Table2
on t1.pid = t2.pid and t1.relation=t2.relation

将此行添加到您的代码中

and t1.relation=t2.relation

答案 2 :(得分:0)

从t1中选择t1.pid,t2.email,t1.mobile,t1关系 内部联接t2 ON t1.pid = t2.pid

相关问题