mysql - 从tbl中选择order_id,其中orders_status_id从不x

时间:2016-08-07 09:16:30

标签: php mysql select

我在我的网站上使用的是带有php版本4的旧mysql版本。

我的表结构:

| orders_status_history_id |  orders_id |  orders_status_id |
|            1             |       22   |         3         |
|            2             |       23   |         2         |
|            3             |       24   |         5         |
|            4             |       23   |         8         |
|            5             |       25   |         5         |
|            6             |       30   |         1         |
|            7             |       26   |         2         |
|            8             |       22   |         4         |
|            10            |       22   |         5         |
|            15            |       48   |         6         |
|            16            |       52   |         8         |
|            17            |       32   |         9         |
|            18            |       50   |         5         |
|            19            |       24   |         5         |
|            22            |       20   |         8         |
|            23            |       1001 |         1         |
|            ..            |       ..   |         ..        |
|            ..            |       ..   |         ..        |

我的表格有200000多行,orders_status_history_idauto increment

所以我的问题是:

我如何获得orders_status_history_id orders_status_id从未拥有orders_id的身份5?

对于examaple:  如果orders_id 22曾经orders_status_id 5然后跳过orders_id 22而orders_id 23从未orders_status_id 5那么请告诉我orders_id 23

所以我希望如此:

| orders_status_history_id |  orders_id | 
|            3             |       24   | 
|            4             |       23   | 
|            17            |       32   | 

因为这些orders_id从未使orders_status_id ID等于5. orders_status_history_id = 3从未有orders_id = 5

我希望你理解。有点难以向你解释。

我试着做这样的事情

$sql = "SELECT orders_status_history_id, orders_id, orders_status_id FROM orders_status_history_tbl where orders_status_id not 5";

但它返回orders_status_id不等于5的所有数组。

Ty求助

如有任何进一步的信息,请问我。

1 个答案:

答案 0 :(得分:2)

<强>已更新

SELECT 
     orders_status_history_id,order_id
FROM 
    orders_status_history_tbl 
Where orders_id NOT IN 
  (
      Select Distinct
          orders_id 
      From 
          orders_status_history_tbl 
      Where 
          orders_status_id = 5
  )