子查询 - 从不相关的表返回数据?

时间:2013-08-09 08:04:36

标签: mysql subquery

只是想知道你是否可以从子查询中获取数据,即使主查询没有返回任何命中?

$query = "SELECT `affiliateID`, `password`, `companyName`, `contactName`,
(SELECT loginAttempts FROM lockoutRecord WHERE attemptedUsername = '$user' AND accountType = 'Affiliate' ) as attemptCount,
(SELECT lastAttemptTime FROM lockoutRecord WHERE attemptedUsername = '$user' AND     accountType = 'Affiliate' ) as lastAttemptTime
FROM `affiliates` WHERE `email` = '$user' LIMIT 1"; 

在上面的示例中,用户的登录尝试在联盟表中找不到该用户的匹配,但我仍然希望它从lockoutRecord返回loginAttempts以查看对该用户进行了多少次尝试名字

谢谢你看看。

1 个答案:

答案 0 :(得分:1)

可能的解决方案

SELECT affiliateID, password, companyName, contactName, loginAttempts, lastAttemptTime
FROM
(
    SELECT '$user' user 
) u LEFT JOIN affiliates a 
    ON u.user = a.email LEFT JOIN
(
    SELECT attemptedUsername, loginAttempts, lastAttemptTime
      FROM lockoutRecord 
     WHERE accountType = 'Affiliate' 
) l ON u.user = l.attemptedUsername

示例输出:

| AFFILIATEID | PASSWORD | COMPANYNAME | CONTACTNAME | LOGINATTEMPTS |     LASTATTEMPTTIME |
--------------------------------------------------------------------------------------------
|      (null) |   (null) |      (null) |      (null) |             2 | 2013-08-09 13:00:00 |

这是 SQLFiddle 演示