简体   繁体   中英

SQL query for matching a column across two tables

I have two SQL tables: users & userGroup with data like:

users :

 user      | age | gender

    testUserA,  25,   Male
    testUserB,  30,   Female
    testUserC,  35,   Male

userGroup :

user     | group

testUserA, groupA
testUserB, groupA
testUserC, groupB

How would I phrase a query to list the male users in groupA?

All you need is a join and a where clause to filter gender and group :

select u.user
from user u
join userGroup ug on u.user = ug.user
where u.gender = 'Male'
  and ug.group = 'groupA'

This query would join the two tables together and also filter by gender.

SELECT u.User, u.Gender, ug.Group
FROM user u
INNER JOIN userGroup ug
ON u.user = ug.user
WHERE u.gender = 'Male'
AND ug.Group = 'groupA';

Here's one way to do it:

select a.user, a.age, a.gender, b.group from users as a 
inner join userGroup as b on a.user=b.user 
where a.gender='Male' and b.group='groupA'

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