0

我有 2 张桌子。

table one: items
table two: items_options

现在我需要在表二上搜索 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

如果没有 group by/have 怎么办?

4

3 回答 3

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

或者

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
于 2012-08-09T21:32:45.067 回答
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
于 2012-08-09T21:32:14.780 回答
0

使用ORhere 而不是AND. AND表明这两种情况可以同时发生。由于您正在寻找具有 的行以及具有 的option_id = 60143行,因此option_id = 60142usingOR将获得具有其中任何一个的行。

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 
于 2012-08-09T21:33:59.700 回答