SQL查询以从另一个表中选择与表的单行上的值相关的多项

问题描述

orderTb: **id_order** **qty** **id_user** **updatedby**
           1             5         2            1

userTb:  **id** **name**
           1      paul
           2      mark

这是我的两个表,希望执行一个mySQL查询以返回:id_order,qty,id_user作为name1,updatedby作为name2。我已经尝试过此查询,但无法正常工作:

select orderTb.id_order,orderTb.qty,userTb.name as name1,userTb.name as Name2 
from orderTb,userTb where orderTb.id_user=userTb.id OR 
orderTb.updatedby=userTb.id

解决方法

您必须两次加入userTb

select orderTb.id_order,orderTb.qty,user.name as name1,userUpdate.name as Name2 
from orderTb user join userTb on orderTb.id_user=user.id 
join userTb userUpdate on orderTb.updatedby=userUpdate.id
,

使用它。

SELECT o.id_order,o.qty,u1.name as name1,u2.name as name2 
FROM orderTb o
INNER JOIN userTb u1 ON u1.id=o.id_user
INNER JOIN userTb u2 ON u2.id=o.updatedby;

在此处查看演示:DB-Fiddle

,

您需要使用JOIN clause才能实现。

您将需要2个JOIN子句到userTb:一个子句将id_user链接到我们称为userTb的{​​{1}},另一个子句将{{ 1}}列,另外一个我们称为userTb1的{​​{1}}:

updatedby