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

标签 php mysql select join associations

我正在创建一个游戏,并且需要根据单行中列出的 ID 值从表 (Table1) 中选择名称。

行的示例

RowID Unit1 Unit2 Unit3 Unit4

And say that row 1 is populated with data for units as

wfmatch

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

Then in my second table (Table2) I have the actual names

wfunits

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

In one query or as close as possible I would like to be able to obtain the names for the ID's listed from the first table giving a result like so:

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

I have had a go with JOIN statements but I have so far been lacking in the knowledge on how to use them properly and I feel this is probably the way to get the result, I just can't figure it out.

Edit: Attempted Code

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

关于php - 将链接数据从一个表中的一行提取到另一表中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10774469/

相关文章:

php - mySQL inner join with where条件不起作用

mysql - SQL查询失败,42000 1064

php - 管理员确认后登录

php - 半复杂的 PHP/MySQL Select 语句

php - 如何从服务器接收图像到应用程序

javascript - 如何像这样重定向到其他网站

php - 2147483647 即使数据类型为 VARCHAR 也被插入到 DB 字段中

php - 如何使用循环从 php 单元格中检索和显示包含对象的数组?

javascript - 根据元素单击更改选择选项值

php - 为 SELECT...BETWEEN 查询创建正确的日期格式