我想知道如何在laravel 5.6中编写下面的sql查询
我的ID来自用户$input = \Auth::user()->id
SELECT t1.*,
t2.*
FROM
(SELECT suggestions.*,
suggestions.id AS sug_id,
users.id AS users_id,
users.name AS user_name,
sum(votes.vote) AS total,
sum(CASE WHEN votes.vote = 1 THEN 1 ELSE 0 END) upvotes,
sum(CASE WHEN votes.vote = -1 THEN 1 ELSE 0 END) downvotes,
GROUP_CONCAT(votes.user_id) AS users_votes,
GROUP_CONCAT(votes.vote) AS votes_status
FROM users
JOIN suggestions ON users.id = suggestions.user_id
JOIN votes ON suggestions.id = votes.sug_id
WHERE suggestions.status = 1
GROUP BY suggestions.id
ORDER BY total DESC) AS t1
LEFT JOIN
(SELECT votes.user_id,
votes.vote AS vote_status,
suggestions.id AS sug_id
FROM votes
JOIN suggestions ON suggestions.id = votes.sug_id
WHERE votes.user_id = $input
GROUP BY sug_id
UNION SELECT '','','') AS t2 ON t1.sug_id = t2.sug_id
这是我以前的代码,但我不知道如何使用另一个select和join
修改它Suggestion::select('suggestions.*','suggestions.id as sug_id','users.id as users_id','users.name as user_name')
->addSelect(DB::raw('sum(votes.vote) as total'))
->addSelect(DB::raw('sum(case when votes.vote = 1 then 1 else 0 end) as upvotes'))
->addSelect(DB::raw('sum(case when votes.vote = -1 then 1 else 0 end) as downvotes'))
->addSelect(DB::raw('GROUP_CONCAT(votes.user_id) as users_votes'))
->addSelect(DB::raw('GROUP_CONCAT(votes.vote) as type_votes'))
->from('users')
->join('suggestions', function($join) {
$join->on('users.id', '=', 'suggestions.user_id');
})
->join('votes', function($join) {
$join->on('suggestions.id', '=', 'votes.sug_id');
})
->where('suggestions.status', '=', 1)
->groupBy('suggestions.id')
->orderByRaw('total DESC')
->get();
答案 0 :(得分:0)
您必须单独引用表名和列名:
`t1.*` → `t1`.`*`