SQL查询未显示具有多个AND和OR子句的所需结果

时间:2018-11-20 11:40:58

标签: mysql sql

我的以下查询未显示期望的结果。我不明白我在哪里用错了括号

查询:

SELECT `orders`.*, `users`.`fullname`, `users`.`phone`
FROM `orders`
JOIN `users` ON `orders`.`userId` = `users`.`id`
WHERE `orders`.`payment_verified_status` = '1'
AND (`orders`.`restId` = 132 OR `orders`.`restId` = 133 OR `orders`.`restId` = 134)
AND (`rest_brId` != 156 OR `rest_brId` != 188 OR `rest_brId` != 157 OR `rest_brId` != 691 OR `rest_brId` != 158)

结果即将到来: enter image description here

但是这些行不应该出现,因为我在查询中提到了rest_brId != 156

请帮助。谢谢!

2 个答案:

答案 0 :(得分:6)

使用declare global { interface String { padZero(length: number): string; } } String.prototype.padZero = function (length: number) { let d = String(this) while (d.length < length) { d = '0' + d; } return d; }; console.log('hi'.padZero(5)) export {}

in

请注意SELECT o.*, u.`fullname`, u.`phone` FROM `orders` o JOIN `users` u ON o.`userId` = u.`id` WHERE o.`payment_verified_status` = 1 AND o.`restId` IN (132, 133, 134) AND ?.`rest_brId` NOT IN (156, 188, 157, 691, 158) 。这是?的talbe别名。

您的逻辑问题是rest_brID表示不等于括号,而不是括号。逻辑的该部分始终求值为true,因为对于该逻辑部分,您实际上想要OR而不是AND

答案 1 :(得分:2)

您的WHERE子句的这一部分不正确:

(`rest_brId` != 156 OR `rest_brId` != 188 OR `rest_brId` != 157 OR `rest_brId` != 691 OR `rest_brId` != 158)

如果rest_brId = 156,虽然该子句的第一部分不正确,但第二到第五部分(例如rest_brId != 188)是正确的,因此该行进入您的输出。您需要将该行更改为:

(`rest_brId` != 156 AND `rest_brId` != 188 AND `rest_brId` != 157 AND `rest_brId` != 691 AND `rest_brId` != 158)

或按照@GordonLinoff的建议使用NOT IN子句。