简体   繁体   中英

PHP MySQL - Select members with where-clause statements from different tables

I've been Googling for most of my day now but I can't seem to find the right answer. Maybe because I don't really know in which direction to look (join? exist?). What I have is 3 tables:

解释表设置


There is a table named 'groups' and 'languages' containing the actual group- and language data but that's not important right now.

The user should be able to generate a list with all members, depending on the selected groups and/or languages. The groups/languages that the user selected are saved in two separate array's containing the IDs ( $aGroups and $aLangs ).

What I want/need is to SELECT * FROM members WHERE ...

And that's where I got stuck. I've tried joins, I've tried IN() , I've tried EXIST but nothing seems to work right.

Any help is greatly appreciated!

I think you just need some brackets:

//assuming you have ids stored in $lang and $group
SELECT * FROM members WHERE (SELECT group_id FROM group_members WHERE member_id=members.id)='$group'
AND (SELECT lang_id FROM language_members WHERE member_id=members.id)='$lang' 

The trick is "members.id", DB will call subquery for every member to find out if the condition for group and lang is met.

If you want to select members by languages and groups, you can do something like this :

$query = "select * from members as m 
left join group_members as gm on gm.member_id = m.id 
left join language_members as lm on lm.member_id = m.id";
if(isset($aGroups)) {
  $query .= " where group_id in (".implode(",", $aGroups).")";
  if(isset($aLangs)) {
    $query .= " and language_id in (".implode(",", $aLangs).")";
  }
} 
elseif(isset($aLangs)) {
  $query .= " where language_id in (".implode(",", $aLangs).")";
}
Select m.* FROM members m, group_members gm, language_members lm
WHERE
lm.member_id=m.id AND
m.id=gm.member_id AND
<<<< START YOUR OWN WHERE HERE.

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