简体   繁体   中英

PHP Mysql, to fetch a common values in an array within a single query

I'm having trouble in fetching common values in table, let me explain, i'm having table named as group_id, here there are 3 columns groupid, userid, id, in query i'm passing array of groupids now in the result i'm getting all the users in all the groups for which i'm passing, for that i'm using following code:

public function enlistusers($groupid) {
        $select = $this->_table->select();
        $select->from(array('a' => 'groups'),array());        
        $select->where ('a.groupid IN (?)',$groupid);
$rows = $this->_table->fetchAll($select)->toArray();
        if(empty($rows)) { return null; }
        return $rows;
}

After fetching all users i want the common users in all the groups for the groupid's which i'm passing, is there any mysql statement to do that within this query only to make it efficient? Any suggention will be appreciated.. Thank you.

I'm not familiar with the mysql class you're using, but the way to do what you want in pure mysql query is like this:

"SELECT *
FROM a as groups
WHERE a.groupid IN ".implode(',',$groupid)."
GROUP BY id
HAVING COUNT(DISTINCT a.groupid) = ".count($groupid);

change the "GROUP BY id" to something else, if you don't have the id column

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