dongsuichi6529 2018-05-14 20:24
浏览 61
已采纳

SQL如果值与多列相似,请选择该列

I need to create a autocomplete search with ajax. The suggestions should only contain the 10 most entered results. The search query has to check multiple columns if the value is like my variable.

But my problem is to create the query and the php logic for that.

  1. Is there any plugin or something simular for that?
  2. How can I select a column if the value in it is like my variable?
  3. I need to create a count query, which counts (in all columns) "how often is here the full word (splitted by spaces)" <- which is like the found one (to get the relevance)

At the end I need to sort the found entries by their relevance to provide the 10 most relevant entries.

(The real query checks for more columns than just 2, but for dummy reasons are 2 okay)

The query which selects the rows where the value is like...

select * from 
(
    (select department from entries where department like '%myVariable%') 
OR 
    (select grade from entries where grade like '%myVariable%')
)

I think you know what I mean. Does anyone have any hints, suggestions, examples or useful links for me?

Thanks in advance!

Best regards,
FriaN

  • 写回答

1条回答 默认 最新

  • dty5753 2018-05-14 20:26
    关注

    Why not use union all here?

    select department from entries where department like '%myVariable%'
    union all
    select grade from entries where grade like '%myVariable%'
    

    Then this should order the results for you:

    select department, count(*) cnt from (
    select department from entries where department like '%myVariable%'
    union all
    select grade from entries where grade like '%myVariable%')a
    group by department
    order by count(*) desc
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题