zoukankan      html  css  js  c++  java
  • CSDN论坛上见到的一道sql问题

    见:http://topic.csdn.net/u/20100625/21/cb7295e6-0514-4e28-888f-2935537208f4.html

    有个表pages ,有5个属性,id, url, title, body, site.
    问: 用一条SQL语句搜出url,body,或site中包含’test’字符串的数据,且将含有‘test’的url 的结果放在最前面,其次是body, 然后是site 且不能有重复数据

    1. 如:

    id url title body site
    1 'a' 'b' 'c' 'd'
    2 'a' 'b' 'c' 'test'
    3 'a' 'b' 'test' 'd'
    4 'ftest' 'b' 'c' 'd'
    5 'test' 'b' 'test' 'test'
    搜出的结果是:
    id url title body site
    4 'ftest' 'b' 'c' 'd'
    5 'test' 'b' 'test' 'test'
    3 'a' 'b' 'test' 'd'
    2 'a' 'b' 'c' 'test'

    ============================================================

    创建测试数据:

    CREATE TABLE pages(id int,url nvarchar(100),Title nvarchar(100),body nvarchar(100),site nvarchar(100))
    INSERT pages SELECT 1, 'a', 'b','c','d'
    UNION ALL SELECT 2, 'a', 'b','c','test'
    UNION ALL SELECT 3, 'a', 'b','test','d'
    UNION ALL SELECT 4, 'ftest', 'b','c','d'
    UNION ALL SELECT 5, 'ftest', 'b','test','test'
    UNION ALL SELECT 6, 'fffffffffff', 'testb','testc','d'
    GO

    执行查询:

    (1)

    select * from pages

    id          url          Title          body            site
    ----------------------------------------------------------------------
    1           a               b           c               d
    2           a               b           c               test
    3           a               b           test            d
    4           ftest           b           c               d
    5           ftest           b           test            test
    6           fffffffffff     testb       testc           d

    (6 行受影响)

    (2)

    select * from pages where url like '%test%' or body like '%test%' or site like '%test%'
    order by case
    when url like '%test%' then 0
    when body like '%test%' then 1
    when site like '%test%' then 2 end

    id          url         Title           body            site
    -----------------------------------------------------------------------
    4           ftest           b           c               d
    5           ftest           b           test            test
    6           fffffffffff     testb       testc           d
    3           a               b           test            d
    2           a               b           c               test

    (5 行受影响)


  • 相关阅读:
    Android之绚丽的图片游览效果--有点像W7效果,透明的倒影,层叠的图片,渐变的颜色透明度
    小程序自定义弹出框
    从零学React Native之04自定义对话框
    ajax的content-download时间过慢问题的解决与思考
    小程序
    使用自定义视图的AlertDialog
    Android浮动按钮
    android 实现微信分享多张图片的功能
    AndroidUI多线程网络请求更新导致BUG
    ==比较时的坑
  • 原文地址:https://www.cnblogs.com/gdjlc/p/2086897.html
Copyright © 2011-2022 走看看