我猜自一个月以来,我一直在努力1次锻炼,希望您能帮助我。我尝试通过多种方式从,与表或联接表中进行子查询,但未收到正确的结果。
好。表1中的一行存储如下信息:
客户编号
名字
lastame
服务员编号
表2中的一行存储如下信息:
userID(客户端和服务员是用户)
名字
姓
我是SQL的新手,但是我看到的是:
WITH waiter AS(
SELECT
waiter_id,
firstname,
lastname
FROM Table1
JOIN Table2 ON Table1.waiter_id = Table2.user_id
)
SELECT
client_id,
firstname as Firstname_client,
lastname as Lastname_client,
waiter_id,
waiter.firstname as Firstname_waiter,
waiter.lastname as Lastname_waiter
FROM Table1
JOIN waiter ON Table1.waiter_id = waiter.waiter.id
如有任何线索,我将不胜感激!
最佳答案
您可以尝试此查询。只需使用别名和JOIN
测试DLL
CREATE TABLE Table1(
client_id int,
firstname varchar(50),
lastname varchar(50),
waiter_id int
);
INSERT INTO Table1 values (1,'Andrew','x',5);
INSERT INTO Table1 values (2,'Chris','xx',6);
INSERT INTO Table1 values (3,'Anna','xxx',7);
INSERT INTO Table1 values (4,'Julia','xxxx',8);
CREATE TABLE Table2(
user_id int,
firstname varchar(50),
lastname varchar(50)
);
INSERT INTO Table2 values (1,'Andrew','x');
INSERT INTO Table2 values (2,'Chris','xx');
INSERT INTO Table2 values (3,'Anna','xxx');
INSERT INTO Table2 values (4,'Julia','xxxx');
INSERT INTO Table2 values (5,'Mat','xxxxx');
INSERT INTO Table2 values (6,'Kathy','xxxxxx');
INSERT INTO Table2 values (7,'Pual','xxxxxxx');
INSERT INTO Table2 values (8,'John','xxxxxxxx');
询问
SELECT t1.client_id ,
t1.firstname AS Firstance_client,
t1.lastname as Lastname_Client,
t1.waiter_id,
t2.firstname as Firstname_waiter ,
t2.lastname as Lastname_Waiter
FROM Table1 t1
inner join Table2 t2 on t1.waiter_id = t2.user_id
sqlfiddle
[结果]:
| client_id | Firstance_client | Lastname_Client | waiter_id | Firstname_waiter | Lastname_Waiter |
|-----------|------------------|-----------------|-----------|------------------|-----------------|
| 1 | Andrew | x | 5 | Mat | xxxxx |
| 2 | Chris | xx | 6 | Kathy | xxxxxx |
| 3 | Anna | xxx | 7 | Pual | xxxxxxx |
| 4 | Julia | xxxx | 8 | John | xxxxxxxx |
关于mysql - 一行中有2个ID,另一行中有名字和姓氏。如何从其他表中接收名字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51474591/