PHP,MySQL选择,按字段排序并将其分组

时间:2017-01-31 22:28:26

标签: php mysql select subquery sql-order-by

欢迎!

我的SQL查询有问题。

我的每个用户都有一个包含已查看标签的唯一表格。我想告诉他他能引起什么兴趣,但我无法应对数据库的查询......

用户X有标签:

tag_id 8 viewed 150 times
tag_id 11 viewed 100 times
tag_id 12 viewed 80 times

这里我的QUERY

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 将被省略。

你知道了吗?

这就是我所说的:

对于TAGS: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 |

仅限唯一身份证明。我知道我可以用SUBQUERY来做,但我不知道怎么做。你能帮忙吗?

美好的一天!

1 个答案:

答案 0 :(得分:0)

我确信这里有更多的子查询,而不是严格必要的,但由于某些原因,如果没有它们,我就无法让它工作......

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;