2017-08-24 79 views
2

我有麻烦了以下任务完成:SQL选择两个用户ID为不同的别名

我有2个表:

User: 
    -uid 
    -username 

challenge: 
    -cID 
    -challengerID 
    -challengedID 

现在我想从c#应用与运行insert into (!每例如挑战user1user2

现在SQL是:

insert into challenge (challengerID, challengedID) 
where challengerID = id of user1 and challengedID = id of user2. 

如何抓住这两个user IDs并将它们存储在挑战表的不同字段中?

+0

您正在使用哪个[DBMS](https://en.wikipedia.org/wiki/Database)? Postgres的?甲骨文? DB2?火鸟? –

+0

你怎么知道用户选择什么?如果你已经知道这些ID,为什么你不能直接添加它们?或者你有其他的机制来找到合适的用户? –

+0

事情是它的一个机器人。用户可以更容易地使用提及功能,而不是记住ID或首先将其读出。所以我必须这样做。 – trices

回答

4

使用join

insert into challenge (challengerID, challengedID) 
    select u1.id, u2.id 
    from users u1 join 
     users u2 
     on u1.username = 'user1' and u2.username = 'user2'; 

当编写查询时,你应该使用的名称参数。不要使用名称查询字符串。

+0

哇..这就像一个魅力!非常感谢! 也感谢格式化我的文本..有点新在这里。 。非常感谢:) – trices