选择在规范化表中具有多个匹配项的项目
我有一个存储一堆对象的表。每个对象可以有多种颜色,这些颜色存储在由 object_id 连接的规范化表中。
如果我去
SELECT `object_name` FROM `objects`
LEFT JOIN `object_color` USING `object_id`
WHERE `object_color` IN ('red', 'blue');
,那么我会得到“红色”OR“蓝色”的对象。我需要获取所有“红色”和“蓝色”的对象。如果我去:
SELECT `object_name` FROM `objects`
LEFT JOIN `object_color` USING `object_id`
WHERE `object_color` = 'red' AND `object_color` = 'blue';
那么我什么也得不到,因为每一行中只有一个 object_color 并且不能同时是两者。另外,实际上,颜色是另一个表中带有名称的 id。为了这个问题,我简化了这里的一切。
我需要能够搜索无限数量的颜色。
谢谢
编辑:
object_color仅在object_color表中。
任何物体都会有任何单一的颜色。
I have a table that stores a bunch of objects. Each object can have many colors which are stored in a normalized table connected by the object_id.
If I go
SELECT `object_name` FROM `objects`
LEFT JOIN `object_color` USING `object_id`
WHERE `object_color` IN ('red', 'blue');
Then I get objects that are 'red' OR 'blue'. I need to get all objects that are 'red' AND 'blue'. If I go:
SELECT `object_name` FROM `objects`
LEFT JOIN `object_color` USING `object_id`
WHERE `object_color` = 'red' AND `object_color` = 'blue';
Then I get nothing as there's only one object_color in each line and it can't be both. Also, in actuality, the colors are id's with names in another table. I simplified everything here for the sake of the question.
I need to be able to search for an unlimited number of colors.
Thanks
EDIT:
object_color is only in the object_color table.
And any object will have any single color once.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
顺便说一句,您从未提及
object_color
列源自哪个表。如果它来自object_color
表:上述查询假设给定的object
行不能有多个object_color
行相同的颜色。但是,正如 Joel C 指出的那样,如果一个object
可能具有多个红色或蓝色的object_color
行,则需要不同的查询。 :还有一个解决方案:
Btw, you never mention from which table the
object_color
column derives. If it is from theobject_color
table:The above query assumes that a givenobject
row could have not have multipleobject_color
rows of the same color. However, as Joel C noted, if it were possible for anobject
to have multipleobject_color
rows of red or blue, then that requires a different query. :Yet another solution:
我更喜欢
ON
而不是USING
:假设一个对象不可能有许多具有相同颜色的行。
I prefer
ON
rather thanUSING
:Assuming that it is not possible for an object to have many rows with same colour.
您需要多重加入
You'll need a multi join
如果您使用的 SQL 支持,您也可以使用 INTERSECT。
这将使两个表相交,并且仅显示具有与相同对象名称匹配的红色和蓝色的行。
You can also use INTERSECT if it is supported in the SQL you're using.
This will intersect the two tables and only show rows that have both red and blue color matched with the same object name.