我有两张表,我从
中提取数据ATM
[ID] [所有者] [平衡] [状态]
ATMAvatar
[ATMID] [头像] [管理员] [允许] [有限公司] [限于]
我当前的查询是
SELECT ATM . * , ATMAvatar.Avatar AS User, ATMAvatar.Admin,
ATMAvatar.Allowed, ATMAvatar.Limited, ATMAvatar.Limit,
(SELECT COUNT( * ) FROM ATMAvatar WHERE ATMID = '{SOME ATM ID}') AS UserCount
FROM ATM
JOIN ATMAvatar ON ATM.ID = ATMAvatar.ATMID
WHERE ATM.ID = '{SOME ATM ID}'
AND ATMAvatar.Avatar = '{SOME NAME}'
如果ATMAvatar和ATM都有相对的行,那么效果很好。我希望能够转换这个,这样如果找不到ATMAvatar行,仍然会为任何ATMAvatar列的某些默认值选择ATM。
例如
如果它只是将行返回空,我会很高兴我可以在php中检查它。
修改 我的问题是我在一系列不包含他的行中搜索James McCrawford。我想我需要重新考虑查询的结构
答案 0 :(得分:2)
您可以使用LEFT JOIN
,例如:
SELECT ATM . * , ATMAvatar.Avatar AS User, ATMAvatar.Admin,
ATMAvatar.Allowed, ATMAvatar.Limited, ATMAvatar.Limit,
(SELECT COUNT( * ) FROM ATMAvatar WHERE ATMID = '{SOME ATM ID}') AS UserCount
FROM ATM
LEFT JOIN ATMAvatar ON ATM.ID = ATMAvatar.ATMID
WHERE ATM.ID = '{SOME ATM ID}'
AND (ATMAvatar.Avatar = '{SOME NAME}' OR ATMAvatar.Avatar IS NULL)
无论ATM
中是否有匹配的记录,这都会返回ATMAvatar
的所有记录。结果行中的所有ATMAvatar
相关字段对null
条记录为ATM
,而不包含任何ATMAvatar
。
答案 1 :(得分:0)
试试这个:
SELECT ATM.*,
ATMAvatar.Avatar AS User,
ATMAvatar.Admin,
ATMAvatar.Allowed,
ATMAvatar.Limited,
ATMAvatar.Limit,
( SELECT COUNT(*)
FROM ATMAvatar
WHERE ATMID = '{SOME ATM ID}'
) AS UserCount
FROM ATM
JOIN ATMAvatar ON ATM.ID = ATMAvatar.ATMID
AND ATMAvatar.Avatar = '{SOME NAME}'
WHERE ATM.ID = '{SOME ATM ID}'