Zelí
Zelí

Reputation: 121

SQL select from 2 tables with 2 conditions

Hi i have two tables in mysql and i want to select from both of them and list things with both condicions true.

Friends :
id         iduser     idfriend
0             44            56
1             44            102
2             10             66
3              10            85
4              44            10

Users:
id         name                email                   isonline
44         john          [email protected]                   1
10         joe           [email protected]                    1
185        mark          [email protected]                      0

Example : im user 44 and i want to get all my friends which are online

So i would exec some sql like :

SELECT * FROM friends WHERE iduser=44 AND SELECT FROM * FROM users WHERE isonline=1 

I know i cant do it this way and i also search stackowerflow and i found some which didnt work for me I just want to get something like : (if im user 44)

10 Joe [email protected]

And i dont want to get myself Thank you for all answers

Upvotes: 0

Views: 89

Answers (3)

Dave
Dave

Reputation: 2984

You can do this with JOINS . Joins are used to make a link between two tables generally using a relation. In your case, the relation is user(id) and friends(iduser). Once the join is done, you can select fields from both tables.

SELECT u.* FROM friends f
INNER JOIN users u 
ON f.idfriend = u.id
WHERE f.iduser = 44 AND u.isonline = 1

Upvotes: 0

Mosty Mostacho
Mosty Mostacho

Reputation: 43434

This should work:

select u.* from friends f
join users u on f.idfriend = u.id
where f.iduser = 44 and u.isonline = 1

Upvotes: 3

Sandeep Bansal
Sandeep Bansal

Reputation: 6394

SELECT * FROM friends f
INNER JOIN users u
ON f.idfriend = u.id
WHERE f.iduser = 44 AND u.isonline = 1

Upvotes: 0

Related Questions