更新:在玩了几个小时之后,使用了一个多查询解决方案,并使用了一个只包含父属性的表来确定哪些项需要更新。
对不起,标题太差了,我想不出如何简明地描述这个问题。
我有一组应该与属性有1到1关系的项。
我有一个查询来返回那些数据错误且这种关系已经中断的行(1对多)。我收集这些行来修复它们,并恢复这种1到1的关系。
这是对实际问题的理论简化,但我将根据请求在这里发布示例表模式。
item表:
+------------+------------+-----------+
| item_id | name | attr_id |
+------------+------------+-----------+
| 1 | BMW 320d | 20 |
| 1 | BMW 320d | 21 |
| 2 | BMW 335i | 23 |
| 2 | BMW 335i | 34 |
+------------+------------+-----------+attribute表:
+---------+-----------------+------------+
| attr_id | value | parent_id |
+---------+-----------------+------------+
| 20 | SE | 21 |
| 21 | M Sport | 0 |
| 23 | AC | 24 |
| 24 | Climate control | 0 |
....
| 34 | Leather seats | 0 |
+---------+-----------------+------------+返回具有多个属性的项的简单查询。
SELECT item_id, COUNT(DISTINCT(attr_id)) AS attributes
FROM item GROUP BY item_id HAVING attributes > 1这给了我一个这样的结果集:
+-----------+------------+
| item_id | attributes |
+-----------+------------+
| 1 | 2 |
| 2 | 2 |
| 3 | 2 |
-- etc. --然而,有一个例外。attribute表可以通过表中的父链接来保存树结构。对于某些行,parent_id可以保存另一个属性的ID。这棵树只有一个层次。示例:
+---------+-----------------+------------+
| attr_id | value | parent_id |
+---------+-----------------+------------+
| 20 | SE | 21 |
| 21 | M Sport | 0 |
....我不希望在我最初的查询中检索条目,其中,对于一对相关的属性,它们与属性20和21相关。
I do希望在以下位置检索项目:
所需的示例结果,只需项ID:
+------------+
| item_id |
+------------+
| 2 |
+------------+如何从attributes中加入items并排除这些行?
我是使用临时表,还是可以通过一个查询实现这一点?
谢谢。
发布于 2010-03-11 15:15:07
下面的查询将只提取唯一的项和属性对(或其父项和属性(如果有的话)),从而消除重复项(根据您的请求,属性只能有一个父项,而父属性没有父项)。
SELECT DISTINCT I.item_id AS iid, A.par_id AS aid
FROM
items AS I,
(SELECT AA.attr_id, IF(AA.parent_id = 0, AA.attr_id, AA.parent_id) AS par_id
FROM attribute AS AA) AS A
WHERE I.attr_id = A.attr_id
ORDER BY I.item_id因此,将上面的查询用作计数查询的子表(与上面的A子表使用的方法相同):
SELECT SUB.iid, COUNT(DISTINCT(SUB.aid)) AS attributes
FROM
(SELECT DISTINCT I.item_id AS iid, A.par_id AS aid
FROM
items AS I,
(SELECT AA.attr_id, IF(AA.parent_id = 0, AA.attr_id, AA.parent_id) AS par_id
FROM attribute AS AA) AS A
WHERE I.attr_id = A.attr_id
ORDER BY I.item_id) AS SUB
GROUP BY SUB.iid
HAVING attributes > 1我在示例items表中添加了3行,以适应这种情况,在这种情况下,项目只能链接到带有父属性的属性,而不能链接到父属性本身(即项目3 -> 23和3 -> 20),以及4 -> 23。
运行上面的查询只列出项目2和3,每个项目都有2个属性。
发布于 2010-03-10 18:14:32
您可以通过一个查询来实现这一点:
SELECT
i.item_id,
COUNT(DISTINCT(i.attr_id)) AS attributes
FROM
items i
INNER JOIN
attributes a
ON i.attr_id = a.attr_id
WHERE
a.parent_id = 0
GROUP BY
i.item_id
HAVING
i.labels > 1发布于 2010-03-11 12:57:37
看来,一个查询是不可能的,因为我们没有什么可分组的,也没有什么可排序的。剩下的一件事是执行一些递归调用,但因为mysql中没有递归的SQL,或者属性数据有一个规则,其中所有链接属性attr_id < parent_id都有规则。
https://stackoverflow.com/questions/2419324
复制相似问题