我有几个已加入的表。我试图只选择那些没有插入行的那些。
示例一。我选择这样的用户:
SELECT *
FROM user_accounts AS ua
INNER JOIN users AS u ON u.id = ua.user_id
INNER JOIN account_profile_entries AS ape ON ape.user_account_id = ua.id
INNER JOIN profile_entries AS pe ON pe.id = ape.profile_entry_id
WHERE pe.profile_field_id = 1227 AND pe.value_tinyint = 0;
在这个查询中,我的配置文件字段有1227,其值为0.一切正常。
示例二。我也做了类似的查询,但这次是value_tinyint = 0:
SELECT *
FROM user_accounts AS ua
INNER JOIN users AS u ON u.id = ua.user_id
INNER JOIN account_profile_entries AS ape ON ape.user_account_id = ua.id
INNER JOIN profile_entries AS pe ON pe.id = ape.profile_entry_id
WHERE pe.profile_field_id = 1227 AND pe.value_tinyint = 1;
在这种情况下也可以。
我被困的地方:
当我需要在pe.profile_field_id = 1227中没有条目(行)时选择user_accounts时,我陷入困境 这是我到目前为止所尝试的:
SELECT *
FROM user_accounts AS ua
WHERE ua.id NOT IN (SELECT u.email AS UserEmail
FROM user_accounts AS ua
INNER JOIN users AS u ON u.id = ua.user_id
INNER JOIN account_profile_entries AS ape ON ape.user_account_id = ua.id
INNER JOIN profile_entries AS pe ON pe.id = ape.profile_entry_id
WHERE pe.profile_field_id = 1227)
但是此查询还会返回具有条目1227的用户。
如何修改该查询以仅返回那些在profile_entries表中没有该条目的用户?
答案 0 :(得分:2)
看起来您正在选择电子邮件而不是ID。将您的查询更改为:
SELECT *
FROM user_accounts AS ua
WHERE ua.id NOT IN (SELECT u.id
FROM user_accounts AS ua
INNER JOIN users AS u ON u.id = ua.user_id
INNER JOIN account_profile_entries AS ape ON ape.user_account_id = ua.id
INNER JOIN profile_entries AS pe ON pe.id = ape.profile_entry_id
WHERE pe.profile_field_id = 1227)
答案 1 :(得分:1)
如果行存在,您需要对表不使用LEFT JOIN操作:
SELECT *
FROM user_accounts AS ua
WHERE ua.id NOT IN
(SELECT u.id
FROM user_accounts AS ua
INNER JOIN users AS u ON u.id = ua.user_id
INNER JOIN account_profile_entries AS ape
ON ape.user_account_id = ua.id
LEFT JOIN profile_entries AS pe
ON pe.id = ape.profile_entry_id
AND pe.profile_field_id = 1227)
请注意,我还将pe.profile_field_id = 1227
移动到了JOIN部分,因为如果您使用LEFT JOIN操作并且在左连接表上有连接,如果不再是左连接。
您还需要将子查询中的列更改为ID,因为它是您要与之比较的。