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

时间:2012-05-27 13:52:36

标签: php mysql select join associations

我正在制作游戏,并且需要根据单行中列出的ID值从表格(表1)中选择名称。

行的示例

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语句,但到目前为止我还没有正确使用它们的知识,我觉得这可能是获得结果的方法,我无法理解。< / p>

编辑: 试图代码

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这样的事可能适合你:

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