mysql 多列连接/子查询

mysql join / subquery on multiple columns

我有两个表(插槽和项目)

Table 'slots'

user_id     armor     helmet     weapon                
=======================================            
1           1         5          2
3           NULL      7          2 

那我有

Table 'items'

id     name            type     bonus                
=====================================            
1      Plate Armor     armor    2
2      Katana          weapon   4 
...

我想要的就是得到这样的数组

$equipment = array(
    'armor' => 'Plate Armor',
    'helmet' => 'Plate Helmet',
    'weapon' => 'Katana'
);

如何通过一个查询实现这一目标?我用一个查询来获取插槽,然后循环遍历它们并查询分配的项目,但这似乎效率不高。

你需要为每件装备一个 join,并且需要一个 left join 因为你的用户可能没有装备在插槽上:

SELECT  A.name AS armor, H.name AS helmet, W.name AS weapon
FROM    slots AS S
        LEFT JOIN items AS A
            ON A.id = S.armor
        LEFT JOIN items AS H
            ON H.id = S.helmet
        LEFT JOIN items AS W
            ON W.id = S.weapon
WHERE   S.user_id = 1

这将 return user_id 1

的项目

另一种选择是只做一个LEFT JOIN来获得所有装备,每件装备一行:

SELECT  user_id, AI.type, I.name
FROM   (SELECT distinct type from items) AS AI
        JOIN slots AS S
            ON 1 = 1
        LEFT JOIN items AS I
            ON  I.id IN (S.armor, S.helmet, S.weapon)
            AND I.type = AI.type
WHERE   S.user_id = 3