我有三个表group_sentences、group_sentences_attributes和group_senteces_categories。
我有一个属性数组,正在使用 IN
进行查询(内爆后)。
然后我就有一个类别 ID,因为它们是递归存储的,所以不需要数组。
我需要选择一个与 $attributesArray 最匹配的组编号,当然还有类别。
这是表group_sentences_attributes
+-----+-------+-----------+
| id | group | attribute |
+-----+-------+-----------+
| 1 | 1 | 3564 |
| 2 | 1 | 3687 |
| 3 | 1 | 3689 |
| 4 | 2 | 3687 |
| 5 | 2 | 3564 |
+-----+-------+-----------+
这里是group_sentences_category
+-----+-------+----------+
| id | group | category |
+-----+-------+----------+
| 1 | 1 | 1564 |
| 2 | 1 | 1221 |
| 3 | 1 | 1756 |
| 4 | 2 | 1358 |
| 5 | 2 | 1125 |
+-----+-------+----------+
这是我的查询,但我担心它无法完成工作。
SELECT group_categories.group
FROM group_categories, group_attributes
WHERE group_categories.category = '$category'
AND group_attributes.attribute IN ($attributesArray)
GROUP BY group_categories.group
ORDER BY count(group_attributes.attribute)
如有任何帮助,我们将不胜感激,谢谢。
最佳答案
首先,您查询中的表与问题中的表不匹配。我猜他们只是错过了“句子”。那么,您就没有 join
子句。简单规则:切勿在 from
子句中使用逗号。
group
对于列来说是一个糟糕的名称,因为它是 SQL 中的关键字。以下可能是您正在寻找的内容:
SELECT gc.groupid
FROM group_sentences_attributes sa JOIN
group_sentences_category sc
ON sa.groupid = sc.groupid
WHERE sc.category = '$category' AND
sa.attribute IN ($attributesArray)
GROUP BY sa.groupid
ORDER BY count(sa.attribute);
如果您只需要一行,请在末尾添加 LIMIT 1
。
关于php - 选择最大匹配的外键(组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29448189/