INNER JOIN与更多AND

时间:2012-08-09 21:29:01

标签: mysql sql

我有两张桌子。

table one: items
table two: items_options

现在我需要在表2中搜索2个options_ids

SELECT i.id FROM items as i
INNER JOIN items_options as io ON i.item_id = i.id 
WHERE io.option_id = 60143 AND io.option_id = 60142  
ORDER BY i.xy ASC LIMIT 0,50

如果没有小组/我有什么办法呢?

3 个答案:

答案 0 :(得分:1)

您似乎想要OR或使用IN声明。

SELECT i.id 
    FROM items as i
INNER JOIN items_options as io
    ON i.item_id = i.id 
WHERE io.option_id IN (60143, 60142)
ORDER BY i.xy ASC 
LIMIT 0,50

OR

SELECT i.id 
FROM items as i
INNER JOIN items_options as io 
    ON i.item_id = i.id 
WHERE io.option_id = 60143 OR io.option_id = 60142  
ORDER BY i.xy ASC 
LIMIT 0,50

您不能拥有同时拥有这两个值的option_id

编辑:如果您想要两个值,可以使用UNION ALL查询:

SELECT x.id
FROM
(
  SELECT i.id, i.xy
  FROM items as i
  INNER JOIN items_options as io 
    ON i.item_id = i.id 
  WHERE io.option_id = 60143 
  UNION ALL
  SELECT i.id, i.xy
  FROM items as i
  INNER JOIN items_options as io 
    ON i.item_id = i.id 
  WHERE io.option_id = 60142  
) x
ORDER BY i.xy ASC 
LIMIT 0,50

或者您可以尝试两次加入items_options表:

SELECT i.id 
FROM items as i
INNER JOIN items_options as io1 
  ON i.item_id = io1.id 
INNER JOIN items_options as io2 
  ON i.item_id = io2.id 
WHERE io1.option_id = 60143 AND io2.option_id = 60142  
ORDER BY i.xy ASC 
LIMIT 0,50

答案 1 :(得分:0)

您似乎想要OR代替AND。 items_options中没有任何行满足这两个条件。

WHERE io.option_id = 60143 OR io.option_id = 60142
                           ^^

可替换地,

WHERE io.option_id IN (60143,60142)

您提到不想使用GROUP BY。听起来好像你不想返回重复的items.id值。您可以在SELECT列表之前添加DISTINCT关键字以消除重复:

SELECT DISTINCT i.id FROM items as i

答案 2 :(得分:0)

在这里使用OR而不是AND可能会更好。 AND表明这两个条件可以同时发生。由于您要查找包含option_id = 60143的行以及包含option_id = 60142的行,因此使用OR会获得包含其中任何一行的行。

SELECT i.id FROM items as i
INNER JOIN items_options as io ON i.item_id = i.id 
WHERE io.option_id = 60143 OR io.option_id = 60142  
ORDER BY i.xy ASC LIMIT 0,50