如何运行此MySQL JOIN查询?

时间:2011-11-30 05:08:13

标签: mysql sql database

假设我有两张桌子。

第一个表是人物角色列表。用户可以拥有许多角色。

mysql> select id, user_id, name from personas_personas;
+----+---------+--------------+
| id | user_id | name         |
+----+---------+--------------+
|  8 |       1 | startup      |
|  9 |       1 | nerd         |
| 10 |       1 | close        |
| 12 |       2 | Nerd         |
| 13 |       2 | Startup      |
| 14 |       2 | Photographer |
+----+---------+--------------+
6 rows in set (0.00 sec)

现在,我有另一张名为“审批”的表格。

mysql> select id, from_user_id, to_user_id, persona_id  from friends_approvals;
+----+--------------+------------+------------+
| id | from_user_id | to_user_id | persona_id |
+----+--------------+------------+------------+
|  2 |            1 |          2 |          8 |
|  3 |            1 |          2 |          9 |
+----+--------------+------------+------------+
2 rows in set (0.00 sec)

如果from_user想要批准某个角色to_user,则会插入一条记录。

我正在尝试进行此查询...

给定用户,找到其所有角色。然后,对于每个角色,确定它是否被批准用于某个to_user。如果是,请在结果集中返回is_approved = 1。否则,在结果集中返回is_approved = 0.

所以这就是我开始的地方:

SELECT *
FROM personas_personas
WHERE user_id = 1
LEFT JOIN friends_approvals ON
...but i don't know where to go from here.

因此,最终结果集应包含personas_personas表中的所有列,然后还应包含每个结果的is_approved

2 个答案:

答案 0 :(得分:2)

 SELECT 
   pp.*,
   CASE
     WHEN exists (
         SELECT 
          * 
         FROM 
          friends_approvals fa  
         WHERE 
          fa.from_user_id = pp.user_id AND
          fa.persona_id = pp.id AND
          fa.to_user_id = 2
          )
      THEN 1
      ELSE 0
   END as is_approved

 FROM 
   personas_personas pp 
 WHERE 
   pp.user_id=1

或者,根据您的口味:

 SELECT 
   pp.*,
   CASE
     WHEN fa.from_user_id IS NOT NULL
      THEN 1
      ELSE 0
   END as is_approved

 FROM 
   personas_personas pp 
     LEFT OUTER JOIN friends_approvals fa ON
       pp.user_id = fa.from_user_id AND
       pp.id = fa.persona_id AND
       fa.to_user_id = 2
 WHERE 
   pp.user_id=1

答案 1 :(得分:2)

如果我正确理解您的需求,您可以这样做:

SELECT personas_personas.*,
       CASE WHEN friends_approvals IS NULL THEN 0 ELSE 1 END AS is_approved
  FROM personas_personas
  LEFT
 OUTER
  JOIN friends_approvals
    ON friends_approvals.from_user_id = ...
   AND friends_approvals.to_user_id = personas_personas.user_id
   AND friends_approvals.persona_id = personas_personas.id
 WHERE personas_personas.user_id = ...
;

这将找到具有指定personas_personas的每个user_id记录,以及指示该用户是否已被指定的from_user_id“批准”的指示符。< / p>

(如果你想要什么,那么请澄清!)