我正在尝试运行此SQL查询:
SELECT
r.sequence, r.status, r.title, r.duedate,
r.related_customer, r.added_by
FROM
reminders r, reminders_users ru
WHERE
r.sequence = ru.reminder_seq
AND (ru.type = 'user' AND ru.value = '2')
OR (ru.value = 'admin' OR ru.value = 'technical_support'
OR ru.value = 'sales' OR ru.value = 'accounts')
AND r.sequence > '0'
ORDER BY
field(status, '', 'Completed'), duedate ASC
然而,其返回结果为ru.value = '3'
要返回的行是:
reminders.sequence = '883'
reminders_users.reminder_seq = '883'
reminders_users.type = 'user'
reminders_users.value = '3'
我无法看到它如何显示为reminders_users.value = '3'
而非'2'
答案 0 :(得分:1)
查看值' 2',' user',' admin'等,您可能会混淆列值和类型。此外,当混合AND和OR时,请确保直接使用括号。
除了使用显式连接而不是长时间过时的逗号分隔连接语法之外,不要在数字上使用引号,而是在同一个字段上使用IN而不是几个OR。
SELECT
r.sequence, r.status, r.title, r.duedate,
r.related_customer, r.added_by
FROM reminders r
JOIN reminders_users ru ON r.sequence = ru.reminder_seq
WHERE r.sequence > 0
AND
(
(ru.value = 'user' AND ru.type = 2)
OR
ru.value IN ('admin', 'technical_support', 'sales', 'accounts')
)
ORDER BY field(status, '', 'Completed'), duedate ASC;