我的目标是让用户和一个最新的入门用户创建,我试图在谷歌上解决但我失败了,所以你是我的最后一次机会。关于我尝试过的事情:
DB::select('SELECT u.id, u.username, u.user_rating,
u.avatar, u.created_at, e.id as e_id, e.title
FROM users u
LEFT JOIN
(
SELECT e.*
FROM entry e
LIMIT 1
) entry AS e ON e.user_id = u.id
ORDER BY u.user_rating DESC
LIMIT 10
我正在使用MySQL
修改
有了它,它不会给我错误,但它不会从加入任何条目:
DB::select('SELECT u.id, u.username, u.user_rating,
u.avatar, u.created_at, e.id as e_id, e.title
FROM users u
LEFT JOIN
(
SELECT e.*
FROM entry e
ORDER BY e.id DESC
LIMIT 1
) AS e ON e.user_id = u.id
ORDER BY u.user_rating DESC
LIMIT 10');
结果:
object(stdClass)#437 (7) {
["id"]=>
int(5002)
["username"]=>
string(6) "Nelosh"
["user_rating"]=>
int(77763)
["avatar"]=>
string(3) "its"
["created_at"]=>
string(19) "2013-12-16 19:20:23"
["e_id"]=>
NULL
["title"]=>
NULL
}
答案 0 :(得分:1)
试试这个:
SELECT u.id, u.username, u.user_rating, u.avatar, u.created_at, e.id AS e_id, e.title
FROM users u
LEFT JOIN (SELECT * FROM (SELECT * FROM entry e ORDER BY e.user_id, e.id DESC) AS e GROUP BY e.user_id) AS e ON e.user_id = u.id
ORDER BY u.user_rating DESC
LIMIT 10;
或强>
SELECT u.id, u.username, u.user_rating, u.avatar, u.created_at, e.id AS e_id, e.title
FROM users u
LEFT JOIN (SELECT * FROM entry e ORDER BY e.user_id, e.id DESC) AS e ON e.user_id = u.id
GROUP BY u.id
ORDER BY u.user_rating DESC
LIMIT 10;
修改::: 强>
SELECT u.id, u.username, u.user_rating, u.avatar, u.created_at, e.id AS e_id, e.title
FROM (SELECT u.id, u.username, u.user_rating, u.avatar, u.created_at FROM users u ORDER BY u.user_rating DESC LIMIT 10) AS u
LEFT JOIN (SELECT e.id, e.user_id, e.title FROM entry e ORDER BY e.user_id, e.id DESC) AS e ON e.user_id = u.id
GROUP BY u.id;
答案 1 :(得分:0)
使用此:
DB::select('SELECT u.id, u.username, u.user_rating,
u.avatar, u.created_at, e.id as e_id, e.title
FROM users u
LEFT JOIN
(
SELECT e.*
FROM entry e
ORDER BY e.created_date DESC //add this condition also
LIMIT 1
) entry AS e ON e.user_id = u.id
ORDER BY u.user_rating DESC
LIMIT 10
答案 2 :(得分:0)
在子查询中,您需要添加ORDER BY以获取最后一个条目。如果你的e.id是自动增量的,你可以这样做:
...
SELECT e.*
FROM entry e
ORDER BY e.id DESC LIMIT 1
...