【发布时间】:2017-06-17 13:01:32
【问题描述】:
欢迎!
我的 SQL 查询有问题。
我的每个用户都有一个带有查看标签的独特表格。我想向他展示什么能引起他的兴趣,但我无法应付对数据库的查询...
用户 X 有标签:
tag_id 8 viewed 150 times
tag_id 11 viewed 100 times
tag_id 12 viewed 80 times
这是我的查询:
SELECT c.id AS cid, c.value, t.id AS tag_id, t.value AS tag_name
FROM components c
JOIN connect_tag_com ctc ON ctc.component_id = c.id
JOIN tags t ON t.id = ctc.tag_id
WHERE t.id IN('8', '11', '12')
ORDER BY FIELD (t.id, '8', '11', '12') ASC, c.id DESC
到这个数据库:http://sqlfiddle.com/#!9/904d1a/6
结果:
| id | value | id | value |
|----|-------------------------|----|------------|
| 8 | article about beetroots | 8 | refreshing |
| 7 | article about pears | 8 | refreshing |
| 5 | article about apples | 8 | refreshing |
| 4 | article about cucumber | 8 | refreshing |
| 1 | article about carrots | 8 | refreshing |
| 8 | article about beetroots | 11 | sweet |
| 7 | article about pears | 11 | sweet |
| 6 | article about berries | 11 | sweet |
| 3 | article about bananas | 11 | sweet |
| 1 | article about carrots | 11 | sweet |
| 8 | article about beetroots | 12 | wegetables |
| 4 | article about cucumber | 12 | wegetables |
| 2 | article about onions | 12 | wegetables |
| 1 | article about carrots | 12 | wegetables |
现在我仍然只按 c.id 组件分组,不幸的是这破坏了整个哲学,因为查询的任务是按照我的观看标签顺序查找材料。因此,如果 c.id 4 具有 标签 8 和 12,则作为查询的结果应该收到仅带有搜索标签的 c.id 4首先,标签 8。第二个标签 - 12 被省略。
你明白了吗?
这就是我所说的:
对于标签:8、11、12
|c.id| value |t.id| value |
|----|-------------------------|----|------------|
| 8 | article about beetroots | 8 | refreshing |
| 7 | article about pears | 8 | refreshing |
| 5 | article about apples | 8 | refreshing |
| 4 | article about cucumber | 8 | refreshing |
| 1 | article about carrots | 8 | refreshing |
| 6 | article about berries | 11 | sweet |
| 3 | article about bananas | 11 | sweet |
| 2 | article about onions | 12 | wegetables |
只有唯一的 ID。我知道我可以用 SUBQUERY 做到这一点,但我不知道该怎么做。你能帮忙吗?
祝你有美好的一天!
【问题讨论】:
-
我不明白 :-(
-
知道了 :) 我想获得一个唯一的 c.ID,以便为 t.ID。如果之前选择了 c.ID,则进一步跳过它。每个 c.ID 可以有多个标签,如果标签稍后再去跳过,并且只归属于第一次。现在你明白了吗?请分析以上附表。谢谢!
-
不。我还是不明白。你能用波兰语总结一下吗?
-
Potrzebuję wybrać z bazy artykuły wg.流行的ności 塔古。 NP。 userX oglądał artykuły najczęściej z tagami: 8, 11 i 12, teraz chcę z bazy wybrać artykuły wg właśnie tej kolejności。 Zatem najpierw artykuły z tagiem 8, później (bez powtórzeń ID) tag 11 i na koniec artykuły z tagiem 12. Jeśli artykuł posiada tag 8 i 11, to wybieram go z tagiem 8, a z 11 pomijam。 Tak jakby sortuję 去 wg。 Priorytetów jakie posiadam。 Podsumowując, potrzebuję wybrać z listy artykuły w kolejności zainteresowania tagiem。
-
啊,好的,我现在明白了。不知何故,我以前看不到您所说的重复是什么意思。选择的标签是否超过 3 个?
标签: php mysql select subquery sql-order-by