我正在尝试获取skill1
,skill2
和&的技能名称。来自table2的skill3
使用Join。
当我试图单独skill1
时,它工作正常。但是,当我尝试获取下一列的详细信息时, 1066不是唯一的表/别名错误。
表1(用户表)
======================================
ID Name skill skill2 skill3
======================================
1 Ed 1 4 3
--------------------------------------
表2(技能详情)
=========================
ID Skill Name
=========================
1 php
2 html
3 css
4 mysql
-------------------------
这是我期望得到的:
[name] => 'Ed'
[skill1] => 'php'
[skill2] => 'mysql'
[skill3] => 'css'
这是我的代码,我正在使用laravel:
DB::table('table1')
->join('table2', function($join)
{
$join->on('table1.skill1', '=', 'table2.id');
})
->join('table2', function($join)
{
$join->on('table1.skill2', '=', 'table2.id');
})
->join('table2', function($join)
{
$join->on('table1.skill3', '=', 'table2.id');
})
->get();
答案 0 :(得分:14)
尝试此查询:
SELECT U.Name AS Name, S1.Skill Name AS Skill1, S2.Skill Name AS Skill2, S3.Skill Name AS Skill3
FROM table1 U
JOIN table2 S1 ON (S1.Id = U.skill1)
JOIN table2 S2 ON (S2.Id = U.skill2)
JOIN table2 S3 ON (S3.Id = U.skill3)
答案 1 :(得分:2)
与@erickmcarvalho查询相同的结果
SELECT Table1.usrname,
(SELECT Table2.skillname FROM Table2 WHERE Table1.skill1 = Table2.Id) As skill1,
(SELECT Table2.skillname FROM Table2 WHERE Table1.skill2 = Table2.Id) As skill2,
(SELECT Table2.skillname FROM Table2 WHERE Table1.skill3 = Table2.Id) As skill3
FROM Table1
仍然会导致4次查询,最好重新构建表格