douduiwei2831 2013-12-04 23:39
浏览 16
已采纳

SQL优化查询

I have a table that has the following records:

    ID | Username | Selected |
   ----------------------------
    1  |  JamesC  |     1    |
    2  |  MikeF   |     0    |
    3  |  JamesC  |     0    |

I wish to have Selected be true for only 1 row where the username is the same. So for example when I set ID = 3 to be Selected = true I wish to setID =1 to have Selected = false as well as any other ID's with the same username.

Right now i'm doing this,

//set all to 0
update table set selected = 0 where username = '$username'

//set unique row to true
update table set selected = 1 where username = '$username' and ID = '$ID';

Is there a better more concise way of achieving the same effect?

  • 写回答

3条回答 默认 最新

  • dongpei2835 2013-12-05 01:52
    关注

    As it was said - not very nice db structure, it is better to have table with unique names and ID of selected item, anyway, you can go with this single query:

    update table set selected=IF(id = '$ID', 1, 0) where username = '$username';
    

    also, try a possible faster variant (test both via explain):

    update table set selected=IF(id <> '$ID', 0, 1) where username = '$username';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化