duancheng1955 2017-02-14 09:56
浏览 170
已采纳

MySQL ORDER BY FIELD可以从内部联接表中获取第二个参数吗?

I got one table which's rows are item_id and tag_id. Every item_id is unique auto implement. item may have several tag_id.

I'm trying to get data sorted like this. When user visit page I catch item_id, go to table, get all tag_ids by item_id and try to return other item_ids which's have same tag_id.

Here is the problem when it returns items_id it is random, first i need to get items by first tag and then other. Here is the SQL query.

    SELECT DISTINCT `item_id`, `rel`.`tag_id`
    FROM `itv_content_tags_rel` AS `rel`
    INNER JOIN ( SELECT `tag_id`
                 FROM `itv_content_tags_rel`
                 WHERE `item_id` = 65736 
                ) 
    AS kk ON kk.`tag_id` = `rel`.`tag_id`
    ORDER BY FIELD(`rel`.`tag_id`, 'rel.tag_id')

The ORDER BY FIELD row not working, [Her is table i got with whis query.][1]

When i change
ORDER BY FIELD(rel.tag_id, 'rel.tag_id')
By

ORDER BY FIELD(`rel`.`tag_id`, '3788') DESC

everything works perfectly [I got sorted table][2]

Is here any solution ?

Edit :

Here is the table i got after Tim's edit. Tim's query Is it possible to get sorted with item_id too like this. First sorted with tag_id then time_id

  • 写回答

1条回答 默认 最新

  • dongtangjie0495 2017-02-14 10:01
    关注

    The reason adding FIELD appears to have fixed the problem is that it puts the 3788 ID first, followed by everything else, which coincidentally just happens to be one other ID. If you want to sort on the tag_id column numerically, then you can just use ORDER BY and cast this column to something numeric:

    SELECT DISTINCT item_id, rel.tag_id
    FROM itv_content_tags_rel AS rel
    INNER JOIN
    (
        SELECT tag_id
        FROM itv_content_tags_rel
        WHERE item_id = 65736 
    ) AS kk
        ON kk.tag_id = rel.tag_id
    ORDER BY CAST(rel.tag_id AS UNSIGNED)
    

    Note that if you plan for the tag_id to only always contain numbers, maybe consider switching the type of this column to a numeric type so you can avoid casts like this in your queries.

    Update: If you also want to sort using the item_id then just add another level to the ORDER BY, i.e. something like this:

    ORDER BY CAST(rel.tag_id AS UNSIGNED),
             CAST(rel.item_id AS UNSIGNED)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题