一行中有2个ID,另一行中有名字和姓氏。如何从其他表中接收名字

时间:2018-07-23 08:32:28

标签: mysql sql join subquery

我猜测自一个月以来我一直在努力1次锻炼,希望您能为我提供帮助。我已经尝试通过多种方式从,与表或联接表中进行子查询,但未收到正确的结果。

好。表1中的一行存储如下信息:

  • 客户编号
  • firsname
  • lastame
  • 侍者ID

表2中的一行存储如下信息:

  • userID(客户和服务员是用户)
  • 名字
  • 姓氏

I've attaced picture how those tables look

我是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

如果有任何线索,我将不胜感激!

2 个答案:

答案 0 :(得分:1)

您可以尝试此查询。只需使用别名和#!/usr/bin/env bash while IFS= read -r file; do [[ -e /some/path/$file ]] && ln -s "/some/path/$file" /dest/path done < file_list

TestDLL

<UserControl.Resources>
    <Style x:Key="RootTreeViewItemStyle" TargetType="TreeViewItem" >
        <Setter Property="IsExpanded" Value="True"/>
    </Style>
</UserControl.Resources>
<TreeView DockPanel.Dock="Left" ItemsSource="{Binding TreeViewModel}" ItemContainerStyle="{StaticResource RootTreeViewItemStyle}">
...
</TreeView>

查询

JOIN

sqlfiddle

[结果]

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');

答案 1 :(得分:0)

您可以使用以下查询获取第三张表

    Select ClientId, 
    c.FirstName as Client_FirstName, 
    c.LastName Client_LastName,
    w.FirstName as Waiter_FirstName, 
    w.LastName as Waiter_LastName, 
    w.UserId as WaiterId
    FROm dbo.Table1 as c
    LEFT JOIN dbo.Waiter as[enter image description here][1] w on c.WaiterId = w.UserId

Sql Snippet