我有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
Dunno为什么 - 最后“ORDER BY position”会破坏一切吗?
答案 0 :(得分:4)
您需要在最外层的查询中应用所有所需的顺序 - 子查询中的ORDERing没有任何意义 - 问题“这个ID是< this list>?”无论列表的顺序如何,都有相同的答案(实际上,更多属性,<此列表>是一个没有订单的集合。)
因此,您需要在最外层的查询中获取所需的所有列。
类似的东西:
SELECT ssi.ID
from
sub_subcategories_id ssi
inner join
subcategories_id si
on
ssi.subcategories_id = si.id
inner join
categories c
on
si.categories_id = c.id
where
c.id = 'X'
order by
c.position,
si.position,
ssi.position
答案 1 :(得分:0)
现在看来,你的查询永远不会返回“一组”数字。如果忽略所有子选择,那么你基本上就是这样做:
SELECT id FROM sub_subcategories_id
ORDER BY position
只会返回一列:sub_sub_categories_id。你最好做一些事情:
SELECT cat.id, subcat.id, subsubcat.id
FROM sub_sub_categories AS subsubcat
LEFT JOIN sub_categories AS subcat ON subcat.id = subsubcat.subcategories.id
LEFT JOIN categories AS cat ON cat.id = subcat.category_id
WHERE (cat.id = 'X')
ORDER BY cat.id, subcat.id, subsubcat.id
这将返回由各种ID排序的3列。如果您不需要单独的sub_sub_categories值,并且只想将它们作为单个字符串值,那么您可以使用GROUP_CONCAT()
并执行各种分组操作:
SELECT cat.id, subcat.id, GROUP_CONCAT(subsubcat.id)
FROM ...
...
WHERE (cat.id = 'X')
GROUP BY cat.id, subcat.id, subsubcat.id
ORDER BY ...