简体   繁体   中英

Join columns from two mysql tables

I'm trying to figure out the following. In the beginning I want to check if a member is in groups 11, 43 or 1.

I have the following tables with columns:

table members (member_id, name, group)
334 Ronald 43
table content (member_id, value)
334 Gold

I'm looking for a query which displays the name FROM members and value FROM content, joined with member_id and end result something like

Ronald Gold

If the user is not in the groups I have set, he/she will not be displayed.

The following is what i have managed to do

$sql = 'SELECT * FROM members m INNER JOIN content p ON m.member_id = p.member_id  ';
$retval = mysql_query( $sql, $conn );    

and

while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo $row['member_id']. " " .$row['value'];
echo "<br>";
}    

will output 334 Gold.

I just need to check the group in the beginning and replace member_id with name in the final output. Any help?

When you're echoing the results if you change echo $row['member_id'] to echo $row['name'] you will get the member's name.

Returning $row['group'] will tell you which group the member is in.

Just adjust your mysql query:

$sql = 'SELECT m.name, p.value FROM members m JOIN content p ON m.member_id = p.member_id WHERE m.group = 1 OR m.group = 11 OR m.group = 43;

then

echo $row['name']. " " .$row['value'];

Also you should be using mysqli_query() or PDO::query() since mysql_query() is deprecated. Reference

Your SQL should return following construct for each row

(member_id, name, group, value)

to filter out members not in desired groups modify your query

$sql = 'SELECT * FROM members m INNER JOIN content p ON m.member_id = p.member_id  WHERE m.group IN (11,43,1) ';

Side note:

Consider using PDO or mysqli_* instead of mysql_* as mysql_* is deprecated and gone in PHP7

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