簡體   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