Mysql连接表

时间:2011-01-24 17:54:15

标签: mysql

我在数据库中有三个表。

第一个表是包含用户信息的表,如下所示:

    id     |     name   |     status    
---------------------------------------
    1      |    john    |      1
    2      |    helen   |      1
    3      |    mike    |      1
    4      |    tina    |      1
    5      |    jim     |      0
    6      |    nina    |      1

第二个表包含某些服务的注册用户:

   sid     |   status  
------------------------
    1      |     1
    2      |     1

第三个表包含其他服务的注册用户:

   oid     |   status  
------------------------
    3      |     1
    4      |     1

我应该进行查询,从第二个和第三个表中找到状态为“1”的所有用户,然后从第一个表中获取所有这些用户的名称和ID(包含用户信息)。此示例的结果如下所示:

   id     |     name   |     status    
---------------------------------------
    1      |    john    |      1
    2      |    helen   |      1
    3      |    mike    |      1
    4      |    tina    |      1

该查询会是什么样的?我应该使用INNER JOIN吗?

3 个答案:

答案 0 :(得分:2)

INNER JOIN是正确的方法。

查询将是

SELECT user.id, user.name, user.status
FROM table1 AS user
INNER JOIN table2 AS service1 ON service1.sid = user.id
INNER JOIN table3 AS service2 ON service2.oid = user.id
WHERE service1.status = 1 AND service2.status = 1

如果您想要服务于service1或service2的用户,则查询可以是

SELECT user.id, user.name, user.status
FROM table1 AS user
WHERE user.id IN (SELECT sid FROM table2 WHERE status=1) OR
      user.id IN (SELECT oid FROM table3 WHERE status=1)

答案 1 :(得分:1)

这将返回第二个表(称为service1)中有一行的用户的id,名称和状态,其中status1是第三个表(service2)中具有status1的行:

INNER JOIN解决方案:

SELECT u.id, u.name, u.status
FROM users u
JOIN service1 s ON s.sid = u.id AND s.status=1
JOIN service2 o ON o.oid = u.id AND o.status=1;

子查询解决方案:

SELECT u.* FROM users u
WHERE u.id IN (SELECT s.id FROM service1 s WHERE s.sid = u.id AND s.status=1)
AND u.id IN (SELECT s.id FROM service2 o WHERE o.oid = u.id AND o.status=1)

在第二个或第三个表中的一个用户的子查询解决方案:

SELECT u.* FROM users u
WHERE u.id IN (SELECT s.id FROM service1 s WHERE s.sid = u.id AND s.status=1)
OR u.id IN (SELECT s.id FROM service2 o WHERE o.oid = u.id AND o.status=1)

答案 2 :(得分:0)

select * from firsttable 
inner join table2 on id = sid and table2.status = 1
inner join table3 on id = oid and table3.status = 1