这是我尝试过的一个例子:
SELECT
*
FROM
(
SELECT
username,
nickname,
email
FROM
accounts
WHERE
id = 1
) AS accdetails,
(
SELECT
rank
FROM
ranks
WHERE
userid = 1
AND group = "admin"
LIMIT 1
) AS rank;
这样可行,但前提是用户在名为“admin”的组中具有排名。如果它不存在,我希望它为等级返回null,但仍然返回用户的用户名,昵称和电子邮件。
我也试过使用左连接,但我似乎也无法正常工作。出现同样的问题。可以使用ON accounts.id=ranks.userid
我怎样才能做到这一点?
答案 0 :(得分:2)
SELECT a.username, a.nickname, a.email, a.id, r.rank
FROM accounts a
LEFT OUTER JOIN ranks r on a.id = r.userid and r.group = 'admin';
答案 1 :(得分:1)
您可以使用左连接
SELECT *
FROM (
SELECT
username,
nickname,
email,
id
FROM accounts
WHERE id = 1
) accdetails
LEFT JOIN
(
SELECT rank
FROM ranks
WHERE userid = 1
AND group = "admin"
LIMIT 1
) ranks on accdetails.id = ranks.userid;