PHP mysql查询无法使用多个" AND"运营商

时间:2018-01-17 07:08:46

标签: php mysql

这是我的查询无效

SELECT p.pID 
  FROM CommunityStoreProducts p  
  JOIN CommunityStoreProductAttributeValues pav 
    ON p.pID = pav.PID 
 WHERE (
      (pav.akID = 62) 
   AND (pav.avID = 12313)
      ) 
   AND (
      (pav.akID = 64) 
   AND (pav.avID = 12315)
     ) 
   AND (
      (pav.akID = 65) 
   AND (pav.avID = 12316)
      )

我还尝试过这样的查询:

SELECT p.pID FROM CommunityStoreProducts p INNER JOIN CommunityStoreProductAttributeValues pav ON p.pID = pav.PID WHERE (pav.akID = 62) AND (pav.avID = 12313)

SELECT p.pID FROM CommunityStoreProducts p INNER JOIN CommunityStoreProductAttributeValues pav ON p.pID = pav.PID WHERE (pav.akID = 64) AND (pav.avID = 12315)

SELECT p.pID FROM CommunityStoreProducts p INNER JOIN CommunityStoreProductAttributeValues pav ON p.pID = pav.PID WHERE (pav.akID = 65) AND (pav.avID = 12316)

所有3个查询都运行良好并返回值。当我们将这个3合1加入1个无法正常工作的查询时。

仅供参考:1件产品满足所有3个条件

第一个查询有什么问题吗?

感谢。

4 个答案:

答案 0 :(得分:3)

我没有看到有关此查询的任何语法错误,但它不会返回任何值。不能有akID同时等于62,64和65的记录。如果要返回所有此类记录,请使用OR运算符:

SELECT p.pID FROM CommunityStoreProducts p
   INNER JOIN CommunityStoreProductAttributeValues pav
      ON p.pID = pav.PID
      WHERE pav.akID = 62 AND pav.avID = 12313
         OR pav.akID = 64 AND pav.avID = 12315
         OR pav.akID = 65 AND pav.avID = 12316

答案 1 :(得分:2)

如果必须使用多个“OR”,则可以用“IN”条件替换它们。

答案 2 :(得分:1)

SELECT p.pID FROM CommunityStoreProducts p INNER JOIN 
CommunityStoreProductAttributeValues pav ON p.pID = pav.PID WHERE 
((pav.akID = 62) AND (pav.avID = 12313)) 
OR
((pav.akID = 64) AND (pav.avID = 12315)) 
OR 
((pav.akID = 65) AND (pav.avID = 12316))

每当您对具有多个条件的相同字段执行操作时,请使用OR而不是AND。

答案 3 :(得分:0)

我正在使用非常复杂的产品过滤器,因此我无法使用" IN"或"或"运营商。现在我改变了这样的查询,它为我工作

SELECT p.pID FROM CommunityStoreProducts p 
INNER JOIN CommunityStoreProductAttributeValues pav620 ON p.pID = pav620.PID 
INNER JOIN CommunityStoreProductAttributeValues pav640 ON p.pID = pav640.PID
INNER JOIN CommunityStoreProductAttributeValues pav650 ON p.pID = pav650.PID
WHERE ((pav620.akID = 62) AND (pav620.avID = 12313))
AND ((pav640.akID = 64) AND (pav640.avID = 12315))
AND ((pav650.akID = 65) AND (pav650.avID = 12316))

我不知道它是否正确,但它对我有用。 谢谢你的回复