dtl85148 2013-08-10 15:48
浏览 23
已采纳

如何设置MySQL查询?

How do I set up this query? I have awards in a table. For example, a trophy may be award_id 1 in the award table. A ribbon may be award_id 2 in the award table. I then have another table, award_user, where it has the award_id and the userid of the user. So, if I wanna give the user the award_id 1, and their userid is 25, it will be in the award_user table as award_id 1 and userid 25 (which means they have that award). I want to select all of the awards the user has based off of their userid.

Here is the thing, though. The awards are in the award table, but the actual user information about the awards are in the award table. So, I will have to select from two different places, I guess.

Here is what I have so far..

$query = mysql_query("SELECT * from award WHERE award_id = (SELECT award_id FROM award_user WHERE userid = $userid)");

Not sure if this will work or not.

Basically, it has to select the awards from the award table with the award_id's that the userid has. $userid is a valid variable, it is their userid.

Thanks!

  • 写回答

2条回答 默认 最新

  • dougu2240 2013-08-10 15:56
    关注

    Your way of expressing the query should work, with one minor tweak. You need to change the = to in, because there can be more than one aware

    SELECT *
    from award a
    WHERE a.award_id in (SELECT au.award_id FROM award_user au WHERE au.userid = $userid)
    

    More typically, this would be expressed as a join:

    select a.*
    from award a join
         award_user au
         on a.award_id = au.award_id
    where au.userid = $userid;
    

    The join form is often more efficient as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!