[英]SQL Query to compare two columns with one column from another table (and get two values)
根据table1
中两列的ID值,是否有可能在table2
获得它们的等效值?
我的table1
看起来像这样:
id | origin | destiny
-- | ------ | -------
1 | 2 | 3
2 | 4 | 5
和table2
,像这样:
id | name
-- | ----
1 | bla
2 | asd
3 | dfg
4 | qwe
5 | tle
我想得到这样的东西:
id | origin | destiny | nameOrigin | nameDestiny
-- | ------ | ------- | ---------- | -----------
1 | 2 | 3 | asd | dfg
2 | 4 | 5 | qwe | tle
我试图做两个查询:
SELECT
t1.origin,
t1.destiny,
t2.name
FROM
table1 t1
INNER JOIN table2 t2 ON t1.origin = t2.id
和:
SELECT
t1.origin,
t1.destiny,
t2.name as destinyName
FROM
table1 t1
INNER JOIN table2 t2 ON t1.destiny = t2.id
但是,如果我从一个表中删除一个值,则另一个表将继续对该行进行索引,因此存在未定义的偏移量问题。
您可以两次连接第二个表:
SELECT t1.id,
t1.origin,
t1.destiny,
o.name as nameOrigin,
d.name as nameDestiny
FROM table1 t1
INNER JOIN table2 o ON t1.origin = o.id
INNER JOIN table2 d ON t1.destiny = d.id
注意: “命运”与“目的地”不同 。
您可以通过简单的查询来做到这一点:
SELECT t1.id,t1.origin,t1.destiny,o.name as nameOrigin, d.name as nameDestiny
FROM t1,t2 o, t2 d
WHERE t1.origin=o.id AND t1.destiny=d.id
我在这里附加SQL小提琴链接。 http://sqlfiddle.com/#!9/ecf5ae
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.