简体   繁体   中英

How to set up MySQL query?

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!

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.

What you need is a join :

SELECT awards.* FROM awards
  JOIN award_user USING (award_id)
WHERE userid = :userid

By the way, learning how joins work is the one thing you really need to do in order to make proper use of SQL. They're what relational databases are all about. If you're using an SQL database but not using joins, it's a bit like, say, having a fancy new computer but only using it to read and write text in Notepad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM