问题
I am creating a game and have come across the need to select the name from a table (Table1) based on the ID value listed in a single row.
Example of the row
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
result: negative, only one name provided.
Working end result:
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
回答1:
You'll probably need four joins, one per column, like this:
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
There's also an alternative, although I'm not sure if it would be better:
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
回答2:
Something like this may work for you:
SELECT *
FROM table1 AS t1
INNER JOIN table2 AS t2 ON t1.id = t2.id
WHERE t1.rowid = ?
来源:https://stackoverflow.com/questions/10774469/extract-linked-data-from-one-row-in-one-table-to-multiple-rows-in-another-table