【问题标题】:How to display the string values of a table refering to Two foreign ID keys on the main table如何显示引用主表上的两个外 ID 键的表的字符串值
【发布时间】:2014-12-03 11:27:05
【问题描述】:

所以我有这个数据库

表格:费率

ID  |  FID  |  TID  |  RATE
---------------------------
 1  |   1   |   2   |  0.3
 2  |   1   |   3   |  1.2
 3  |   1   |   4   |  4.5
 4  |   2   |   1   |  1.3
 5  |   2   |   3   |  3.3
 6  |   2   |   4   |  4.4

表格:货币

ID  |   Name   |  Symbol
---------------------
 1  |   Euro   |   E   
 2  |   Pound  |   P   
 3  |  Dollar  |   $   
 4  |   CAD    |   C

所以到目前为止我尝试的是

SELECT  rates.*,
    currencies.name,
    currencies.symbol FROM RATES 
JOIN CURRENCIES ON
(rates.fid = currencies.id)

这有效,但仅适用于 1 列。我找不到添加更多内容的方法。我还想为每种货币提供一个自定义输出名称。所以最终的输出应该是:

ID | FromCurrency (FID) | ToCurrency (TID) | Rate   

【问题讨论】:

  • 所以你需要像FromCurrency -> EuroToCurrency->Dollar这样的货币名称?
  • 是的。只是前台表的 id 漂亮地显示为与费率表中的 id 相同的名称。
  • SELECT rates.id, currency.name as fromCurrency, currency.name as toCurrency, rates.rate FROM RATES JOIN CURRENCIES ON (rates.fid = currency.id) 虽然我应该是这样的我错过了一些东西。这是不正确的。

标签: mysql join foreign-keys


【解决方案1】:

您需要执行多个连接,并且由于您对两个连接使用同一个表,因此请给它们一个别名。

类似这样的:

SELECT  rates.ID,
    a.name AS 'FromCurrency (FID)',
    a.symbol AS 'FID Symbol',
    b.name AS 'ToCurrency (TID)',
    b.symbol AS 'TID Symbol',
    rates.rate
FROM RATES 
JOIN CURRENCIES AS a ON
(rates.fid = a.id)
JOIN CURRENCIES AS b ON
(rates.tid = b.id)

Here is a working example

【讨论】:

  • 像梦一样工作。谢谢。 “AS”命令是我所缺少的。最终的 SQL 代码是:SELECT rates.id, fc.name as fromCurrency, tc.name as toCurrency, rates.rate FROM RATES JOIN CURRENCIES as fc ON (rates.fid = fc.id) JOIN CURRENCIES as tc ON (rates. tid = tc.id)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
相关资源
最近更新 更多