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
如果没有小组/我有什么办法呢?
答案 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