如何获得两次相同外键的连接值?

时间:2014-05-15 21:15:44

标签: mysql sql

我目前的情况可以通过3个SQL查询轻松解决,但我想知道是否可以在一个查询中完成。

我有以下表格:

  symbol                     similarity
  -------                    ------------

  id | name | latex          id | base_symbol_id | similar_symbol_id

我想选择SELECT,以便我的结果如下所示:

  query_result
  ------------

  similarity_id | base_formula_id | base_formula_name | base_formula_latex | similar_formula_id | similar_formula_name | similar_formula_latex

尝试失败

我通常用JOIN解决类似的任务。但这一次,SELECT取决于我选择的另一个属性......我不知道如何做到这一点。这是我的尝试(当然失败了):

SELECT `base_symbol_id`, `similar_symbol_id`, `latex`
FROM `similarity` 
JOIN `symbol` ON ((`symbol`.`id` = `base_symbol_id`) OR (`symbol`.`id` = `similar_symbol_id`)) 

给出

base_symbol_id | simlar_symbol_id | latex
10             | 11               | \alpha
10             | 11               | a

2 个答案:

答案 0 :(得分:3)

select sim.id
,base.id
,base.name
,base.latex
,similar.id
,similar.name
,similar.latex
from similarity as sim
join symbol as base on base.id=sim.base_symbol_id 
join symbol as similar on similar.id=sim.similar_symbol_id

答案 1 :(得分:2)

使用给定的表格结构,并在 SQL Fiddle session 中组成一些随机样本输入,以下查询可以按您的方式工作:

SELECT T.id as similarity_id, 
      S1.id as base_formula_id, S1.name as base_formula_name, S1.latex as base_formula_latex,
      S2.id as similar_formula_id, S2.name as similar_formula_name, S2.latex as similar_formula_latex
  FROM similarity T
  LEFT OUTER JOIN symbol S1 ON (T.base_symbol_id = S1.id)
  LEFT OUTER JOIN symbol S2 ON (T.similar_symbol_id = S2.id)