我在mysql中测试了这个查询,但它确实有效。 它在矿井控制器中不起作用。有人可以纠正吗?
$albi = DB::table(DB::raw("(SELECT
albi.id,
albi.CoverAlbo,
albi.Nazione,
albi.Editore,
albi.NomeCollanaUfficiale,
albi.AnnoPubblicazione
FROM albi AS a LEFT JOIN albi_user AS au ON a.id = au.albi_id
AND au.user_id = $user_id
WHERE au.albi_id IS NULL)"));
这是错误:
SQLSTATE [42000]:语法错误或访问冲突:1248每个派生表必须有自己的别名
请帮帮我!!!
答案 0 :(得分:0)
您应该使用别名而不是表名。所以试试这个:
$albi = DB::table(DB::raw("(SELECT
a.id,
a.CoverAlbo,
a.Nazione,
a.Editore,
a.NomeCollanaUfficiale,
a.AnnoPubblicazione
FROM albi AS a LEFT JOIN albi_user AS au ON a.id = au.albi_id
AND au.user_id = $user_id
WHERE au.albi_id IS NULL)"));
答案 1 :(得分:0)
这是因为您正在使用DB::table()
,然后在其中放置raw
查询(创建子查询),然后不给它别名。
要使上述代码正常工作,您只需将最后一行更改为:
WHERE au.albi_id IS NULL) as t1")); //notice the "t1" alias
或者你可以DB::select()
:
$albi = DB::select("SELECT
a.id,
a.CoverAlbo,
a.Nazione,
a.Editore,
a.NomeCollanaUfficiale,
a.AnnoPubblicazione
FROM albi AS a LEFT JOIN albi_user AS au ON a.id = au.albi_id
AND au.user_id = $user_id
WHERE au.albi_id IS NULL");
请注意,这与select()
DB::table()->select()
或者您可以使用查询构建器:
$albi = DB::table('albi')
->select('id', 'CoverAlbo', 'Nazione', 'Editore', 'NomeCollanaUfficiale', 'AnnoPubblicazione')
->leftJoin('albi_user', 'albi.id', 'albi_user.alibi_id')
->where('albi_user.user_id', $user_id)
->whereNull('albi_user.albi_id')
->get();
希望这有帮助!