欢迎!
我的 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 |
现在我只剩下 group by 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 做到这一点,但我不知道该怎么做。你能帮忙吗?
祝你有美好的一天!
最佳答案
我确信这里的子查询比绝对必要的要多,但出于某种原因,没有它们我无法让它工作......
SELECT cid
, value
, tag_id
, tag_name
FROM
( SELECT cid
, value
, tag_id
, tag_name
, CASE WHEN @prev = cid THEN @i:=@i+1 ELSE @i:=1 END i
, @prev := cid
FROM
( SELECT c.id cid
, c.value
, t.id tag_id
, t.value 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)
) x
JOIN ( SELECT @prev:=null,@i:=0 ) vars
ORDER
BY value
, FIELD(tag_id,8,11,12) ASC
) n
WHERE i = 1 ORDER
BY FIELD(tag_id,8,11,12) ASC
, value;
关于PHP, MySQL select, order by field and group it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968644/