我正在处理3个包含以下名称和列的表:
$arr = [["From"=>"Jack", "To"=>"Peter"],
["From"=>"Jack", "To"=>"John"],
["From"=>"Jack", "To"=>"Ali"],
["From"=>"Ali", "To"=>"Jack"],
["From"=>"Ali", "To"=>"Martin"],
["From"=>"Jack", "To"=>"Barmar"],
["From"=>"Peter", "To"=>"John"]];
$result = array();
foreach ($arr as $item) {
$result[$item['From']][] = $item;
}
Key = UserID
说明:
问题:
到目前为止,我在下面的 SQL查询:
array (size=3)
'Jack' =>
array (size=4)
0 =>
array (size=2)
'From' => string 'Jack' (length=4)
'To' => string 'Peter' (length=5)
1 =>
array (size=2)
'From' => string 'Jack' (length=4)
'To' => string 'John' (length=4)
2 =>
array (size=2)
'From' => string 'Jack' (length=4)
'To' => string 'Ali' (length=3)
3 =>
array (size=2)
'From' => string 'Jack' (length=4)
'To' => string 'Barmar' (length=6)
'Ali' =>
array (size=2)
0 =>
array (size=2)
'From' => string 'Ali' (length=3)
'To' => string 'Jack' (length=4)
1 =>
array (size=2)
'From' => string 'Ali' (length=3)
'To' => string 'Martin' (length=6)
'Peter' =>
array (size=1)
0 =>
array (size=2)
'From' => string 'Peter' (length=5)
'To' => string 'John' (length=4)
结果是一个空表
*Table 1*
**Users**
UserID UserName UserTypeNumber
1 John 1N
2 Mary 1N
3 Doe 1N
4 Sullivan 2N
5 Sally 1N
**Key = UserID**
*Table 2*
**MobileUsers**
Userid MobileAccess
1 Yes
2 Yes
3 Yes
4 Yes
5 No
**Key = UserID**
*Table 3*
**PanCards**
UserID CARD_NUMBER
3 2222
4 3333
5 1111
但我想要的是返回以下结果:
SELECT MobileUsers.Userid, MobileUsers.MobileAccess
FROM MobileUsers
INNER JOIN Users
ON MobileUsers.Userid = Users.UserID
INNER JOIN PanCards
ON Users.UserID = PanCards.UserID
WHERE MobileUsers.MobileAccess = 'Yes'
AND
Users.UserTypeID = '1N'
AND
MobileUsers.Userid NOT IN
(SELECT PanCards.UserID FROM PanCards)
我如何解决此问题并获得正确的结果?
答案 0 :(得分:4)
如果您想使用LEFT JOIN
,请使用PanCards
SELECT mu.*
FROM MobileUsers mu JOIN
Users u
ON mu.Userid = u.UserID LEFT JOIN
PanCards pc
ON pc.UserID = mu.UserID
WHERE mu.MobileAccess = 'Yes' AND
u.UserTypeID = '1N' AND
pc.UserID IS NULL;
并检查不匹配:
PanCards
我认为您的查询无需加入{{1}}即可。
答案 1 :(得分:1)
WITH NotPan -- First get users that are not in the PanCards table
AS
(
select * from Users as u
where u.userid not in (select userid from PanCards)
)
-- Easy from here
select * from NotPan as n
inner join mobileUsers m on m.userid = n.userid
inner join Users as u on n.userid = u.userid
WHERE m.MobileAccess = 'Yes' and u.UserTypeNumber = '1N'