第一段背景信息:这是关于cms,它保存对象 - 对象关系及其在单个表中的排序,列是object_id,parent_id和排序顺序
第二件有多个连接的查询,我想按2个参数排序。其中一个是对象本身的排序,第二个是其父对象的排序顺序。
我现在的查询是:
SELECT obj_asset.*, object.headline AS title, oo.sort_order AS sort, op.sort_order FROM obj_asset
JOIN object ON obj_asset.object_id = object.object_id
JOIN object_object AS oo on obj_asset.object_id = oo.object_id
JOIN (SELECT sort_order from object_object WHERE object_id = (SELECT parent_id from object_object WHERE object_id = obj_asset.object_id )) AS op ON obj_asset.object_id = oo.object_id
WHERE obj_asset.profile_id = 140 AND obj_asset.rsvp_enabled = 1 AND object.is_published = 1 ORDER BY sort DESC;
它不起作用。这样可以正常工作:
SELECT obj_asset.*, object.headline AS title, oo.sort_order AS sort, op.sort_order FROM obj_asset
JOIN object ON obj_asset.object_id = object.object_id
JOIN object_object AS oo on obj_asset.object_id = oo.object_id
JOIN (SELECT sort_order from object_object WHERE object_id = (SELECT parent_id from object_object WHERE object_id = 11111 )) AS op ON obj_asset.object_id = oo.object_id
WHERE obj_asset.profile_id = 140 AND obj_asset.rsvp_enabled = 1 AND object.is_published = 1 ORDER BY sort DESC;
我得到的错误是:
我怎样才能让它发挥作用?
谢谢!
编辑:我可以解决这个问题,如果我可以提出替代方法来包括父母排序查询。有这样的方式吗?
答案 0 :(得分:1)
正如您已经想到的那样,问题是您尝试在子查询的约束中使用外部查询中的列:
(SELECT sort_order
from object_object
WHERE object_id = (SELECT parent_id
from object_object
WHERE object_id = obj_asset.object_id )
)
可以重写此子查询,但仅查看原始查询时不清楚。
原始查询(重新格式化)可能存在错误:
SELECT obj_asset.*, object.headline AS title, oo.sort_order AS sort, op.sort_order
FROM obj_asset
JOIN object ON obj_asset.object_id = object.object_id
JOIN object_object AS oo on obj_asset.object_id = oo.object_id
JOIN (SELECT sort_order
from object_object
WHERE object_id = (SELECT parent_id
from object_object
WHERE object_id = obj_asset.object_id )
) AS op ON obj_asset.object_id = oo.object_id
WHERE obj_asset.profile_id = 140 AND obj_asset.rsvp_enabled = 1 AND object.is_published = 1 ORDER BY sort DESC;
名为op
的子查询未在任何join或where子句中使用。
我的最佳猜测是您想要的以下内容:
SELECT obj_asset.*, object.headline AS title, oo.sort_order AS sort, op.sort_order
FROM obj_asset
JOIN object ON obj_asset.object_id = object.object_id
JOIN object_object AS oo on obj_asset.object_id = oo.object_id
JOIN (SELECT sort_order, o2.object_id
from object_object as o1
INNER JOIN object_object as o2 ON o1.object_id = o2.parent_id
) AS op ON obj_asset.object_id = op.object_id
WHERE obj_asset.profile_id = 140 AND obj_asset.rsvp_enabled = 1 AND object.is_published = 1 ORDER BY sort DESC;
答案 1 :(得分:0)
您的子查询在FROM子句中不包含obj_asset。
(SELECT parent_id FROM object_object WHERE object_id = obj_asset.object_id )
让这部分运行起来,你应该有更好的运气。
只是一个提示......如果你在SQL语句中添加更多的换行符和缩进词,你就会更容易发现问题。
答案 2 :(得分:0)
我认为您需要输入此内容(包括obj_asset到FROM):
(SELECT parent_id FROM object_object, obj_asset WHERE object_object.object_id = obj_asset.object_id )
但不是这样:
(SELECT parent_id from object_object WHERE object_id = obj_asset.object_id )