假设我有这个 sql 行:
SELECT (something)
FROM user_data, user_profile_image
WHERE user_data.user_id='6' (AND user_profile_image.user_id='6')
如果 user_profile_image 中没有包含与该用户相关的数据,我如何确保它从 user_data 字段返回信息?
SELECT something
FROM user_data
LEFT JOIN user_profile_image
ON user_profile_image.user_id = user_data.user_id
WHERE user_data.user_id = '6'
AND user_profile_image.user_id IS NULL;
You want to LEFT JOIN
the detail page on the foreign key field being equal to the primary key field of the first table, and select the rows from the first table such that there IS no matching row from the second table.
In the query you gave, there's no join criteria, so it would be a Cartesian product - every row of user_data
merged with every single row of user_profile_image
.
您需要使用JOIN
SELECT u.*,i.user_profile_image FROM user_data u LEFT JOIN `USER_PROFILE_IMAGE_TABLE` i ON i.user_id=u.user_id WHERE u.user_id='6'
我不确定你的 USER_PROFILE_IMAGE_TABLE 是什么,所以你需要改变它。
尝试这个:
SELECT u.user_id, u.user_name, IFNULL(up.user_id, 'No Data In user_profile_image') UserId,
IFNULL(up.user_image_id, 'No Data In user_profile_image') user_image_id
FROM user_data u
LEFT JOIN user_profile_image up ON u.user_id = up.user_id
WHERE u.user_id = 6;
检查此链接SQL FIDDLE DEMO