如何从第三个表连接的两个mySQL表中选择数据?

时间:2018-01-19 17:19:27

标签: php mysql

这些是我的表格:

项目:

+----+---------+
| id | project |
+----+---------+
|  1 | cat     |
|  2 | bird    |
|  3 | frog    |
+----+---------+

订单:

+----+------------+
| id | project_id |
+----+------------+
| 21 | 1          |
| 22 | 1          |
| 23 | 2          |
| 24 | 3          |
+----+------------+

产品:

+----+----------+---------+
| id | order_id | status  |
+----+----------+---------+
|  1 |       21 | pending |
|  2 |       21 | ok      |
|  3 |       23 | ok      |
|  4 |       23 | ok      |
|  5 |       22 | ok      |
+----+----------+---------+

我的目标是找出每个项目是否所有产品都“正常”。连接是订单表。

所以这将是我的结果

  CAT = SOME PENDING
  BIRD = ALL OK
  FROG = ALL OK

我有困难,这意味着我被困住了。我不知道如何连接这些表。我的方法:

       $pdo = $db->query('SELECT  * 
       (SELECT COUNT(*) 
       FROM products 
       WHERE projects.project_id=orders.project_id) AS all,
       (SELECT SUM(`status`=`ok`) 
        FROM products 
        WHERE projects.id=orders.project_id) AS ok,
        FROM projects
        group by projects.id
      ')->fetchAll(PDO::FETCH_ASSOC);

1 个答案:

答案 0 :(得分:2)

对项目进行分组,然后检查每个组是否所有记录都正常

   SELECT pj.id, pj.project, 
          case when sum(status <> 'ok') = 0 
               then 'all ok'
               else 'pending'
          end as overall_status
   FROM projects pj
   LEFT JOIN orders o on pj.id = o.project_id
   LEFT JOIN products pr on pr.order_id = o.id
   GROUP BY pj.id, pj.project

这一行:

sum(status <> 'ok') = 0

总结了这种情况的真实程度。必须true永远不会为每个组