繁体   English   中英

将链接数据从一个表中的一行提取到另一表中的多行

[英]Extract linked data from one row in one table to multiple rows in another table

我正在创建一个游戏,遇到了需要根据一行中列出的ID值从表(Table1)中选择名称的情况。

该行的示例

RowID Unit1 Unit2 Unit3 Unit4

并说第1行的单位数据为

wfmatch

RowID Unit1 Unit2 Unit3 Unit4
----- ----- ----- ----- -----
1     1     2     3     4

然后在第二张表( Table2 )中,我有实际的名字

wfunits

UnitID Name
------ ----------
1      Firstitem
2      Seconditem
3      Thirditem
4      Fourthitem

在一个查询中或尽可能接近的查询中,我希望能够从第一个表中获得列出的ID的名称,并给出如下结果:

this is the end result as achieved with code at the bottom. (+4 more names)

RowID Unit1     Unit2      Unit3     Unit4
----- --------- ---------- --------- ----------
1     Firstitem Seconditem Thirditem Fourthitem

我已经熟悉了JOIN语句,但是到目前为止我仍然缺乏如何正确使用它们的知识,我觉得这可能是获得结果的方法,我只是想不通。

编辑:尝试的代码

SELECT * FROM wfmatch AS t1 INNER JOIN wfunits AS t2 ON t1.crunit1 = t2.id WHERE t1.mid = 1

结果:否定,仅提供一个名称。

工作最终结果:

SELECT
m.mid, u1.name AS Unit1, u2.name AS Unit2, u3.name AS Unit3, u4.name AS Unit4,
u5.name AS Unit5, u6.name AS Unit6, u7.name AS Unit7, u8.name AS Unit8
FROM wfmatch AS m  
INNER JOIN wfunits AS u1 ON m.crunit1=u1.id  
INNER JOIN wfunits AS u2 ON m.crunit2=u2.id 
INNER JOIN wfunits AS u3 ON m.crunit3=u3.id 
INNER JOIN wfunits AS u4 ON m.crunit4 =u4.id 
INNER JOIN wfunits AS u5 ON m.counit1=u5.id 
INNER JOIN wfunits AS u6 ON m.counit2=u6.id 
INNER JOIN wfunits AS u7 ON m.counit3=u7.id  
INNER JOIN wfunits AS u8 ON m.counit4 =u8.id 
WHERE mid=1

您可能需要四个联接,每列一个,如下所示:

SELECT
  m.RefID,
  u1.Name AS Unit1,
  u2.Name AS Unit2,
  u3.Name AS Unit3,
  u4.Name AS Unit4
FROM Table1 AS m
  INNER JOIN Table2 AS u1 ON m.Unit1 = u1.UnitID
  INNER JOIN Table2 AS u2 ON m.Unit2 = u2.UnitID
  INNER JOIN Table2 AS u3 ON m.Unit3 = u3.UnitID
  INNER JOIN Table2 AS u4 ON m.Unit4 = u4.UnitID

还有一种选择,尽管我不确定是否会更好:

SELECT
  m.RefID,
  MAX(CASE u.UnitID WHEN m.Unit1 THEN u.Name END) AS Unit1,
  MAX(CASE u.UnitID WHEN m.Unit2 THEN u.Name END) AS Unit2,
  MAX(CASE u.UnitID WHEN m.Unit3 THEN u.Name END) AS Unit3,
  MAX(CASE u.UnitID WHEN m.Unit4 THEN u.Name END) AS Unit4
FROM Table1 AS m
  INNER JOIN Table2 AS u ON u.UnitID IN (m.Unit1, m.Unit2, m.Unit3, m.Unit4)
GROUP BY m.RefID

这样的事情可能适合您:

SELECT *
FROM table1 AS t1
INNER JOIN table2 AS t2 ON t1.id = t2.id
WHERE t1.rowid = ?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM