简体   繁体   English

SQL从具有2个条件的2个表中选择

[英]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. 嗨,我在mysql中有两个表,我想从两个表中进行选择并列出两个条件都正确的东西。

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          john@gmail.com                   1
10         joe           joe@yahoo.com                    1
185        mark          mark@so.com                      0

Example : im user 44 and i want to get all my friends which are online 示例:即时通讯用户44,我想让我所有在线的朋友

So i would exec some sql like : 所以我会执行一些像这样的sql:

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) 我知道我不能用这种方法,而且我也搜索stackowerflow,我发现一些对我不起作用的东西,我只想得到类似的东西:(如果我是用户44)

10 Joe joe@yahoo.com 10乔joe@yahoo.com

And i dont want to get myself Thank you for all answers 而且我不想让我自己谢谢所有的答案

This should work: 这应该工作:

select u.* from friends f
join users u on f.idfriend = u.id
where f.iduser = 44 and u.isonline = 1
SELECT * FROM friends f
INNER JOIN users u
ON f.idfriend = u.id
WHERE f.iduser = 44 AND u.isonline = 1

You can do this with JOINS . 您可以使用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). 在您的情况下,该关系是user(id)和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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM