SELECT * FROM 表 WHERE 字段 IN (SELECT id FROM 表 ORDER BY 字段2)
我有 4 个表:
categories - id, position
subcategories - id, categories_id, position
sub_subcategories - id, subcategories_id, position
product - id, sub_subcategories_id, prod_pos
现在我正在进行测试以找出我的查询出了什么问题。
所以我想选择 sub_subcategories,并得到类似的内容:
[[1,2,3,4,5,6], [1,2,3,4,5,6,7]], [[1,2,3,4,5,6], [1,2,3,4]]
每个 [] 表示:大 - 类别,小 - 子类别,并且数字位于 sub_subcategories 中。我希望 [] 按其“位置”字段进行排序,因此查询:
SELECT id FROM sub_subcategories_id
WHERE subcategories_id IN (
SELECT id
FROM subcategories_id
WHERE categories_id IN (
SELECT id FROM categories
WHERE id = 'X' ORDER BY position)
ORDER BY position)
ORDER BY position
在某种程度上是错误的,因为我得到:
1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,6,6,6,7
不知道为什么 - 最后一个“按位置排序”会破坏所有内容吗?
I have 4 tables:
categories - id, position
subcategories - id, categories_id, position
sub_subcategories - id, subcategories_id, position
product - id, sub_subcategories_id, prod_pos
Now I'm doing tests to find out what's wrong with my query.
So i want to select sub_subcategories, and to get someting like that:
[[1,2,3,4,5,6], [1,2,3,4,5,6,7]], [[1,2,3,4,5,6], [1,2,3,4]]
Each [] means: big - categories, small - subcategory, and the numbers are position in sub_subcategories. I want the [] to order by their "position" field, so query:
SELECT id FROM sub_subcategories_id
WHERE subcategories_id IN (
SELECT id
FROM subcategories_id
WHERE categories_id IN (
SELECT id FROM categories
WHERE id = 'X' ORDER BY position)
ORDER BY position)
ORDER BY position
is somehow wrong, because I get:
1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,6,6,6,7
Dunno why - does last "ORDER BY position" destroy everything?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在最外层查询中应用所有所需的排序 - 子查询内的排序没有任何意义 - 问题“此 ID 在 <此列表> 中吗?”具有相同的答案,无论列表的顺序如何(事实上,more 属性,是一个集合,没有顺序)。
因此,您需要获取最外层查询中需要排序的所有列。
像这样的东西:
You need to apply all of your desired ordering in the outermost query - ORDERing within subqueries doesn't make any sense - the question "is this ID in <this list>?" has the same answer, no matter what order the list is in (indeed, more property, <this list> is a set, which has no order).
So you'll need to get all of the columns you need to order by in your outermost query.
Something like:
就目前而言,您的查询永远不会按原样返回一组数字。如果您忽略所有子选择,那么您实际上是在做:
这只会返回一列:sub_sub_categories_id。您最好执行以下操作:
这将返回按不同 ID 排序的 3 列。如果您不需要单独的 sub_sub_categories 值,而只想将它们作为单个字符串值,则可以使用
GROUP_CONCAT()
并进行各种分组:As it stands now, your query would never return a 'set' of numbers as is. If you ignore all the subselects, you're essentially doing:
which would only return one column: the sub_sub_categories_id. You'd be better off doing something like:
That'll return 3 columns ordered by the various IDs. If you don't need the individual sub_sub_categories values, and just want them as a single string value, you can mess around with
GROUP_CONCAT()
and do various bits of grouping: