-1

i have trouble with mysql, i dont find the way to do it maybe i dont know the good mysql keyword

mysql5

+----------+------------+----------+
| ID       | FOREIGNKEY |  TRAINER |
+----------+------------+----------+
|      ... | ...        | ...      |
|      475 | 254        |  NULL    |
|      476 | 254        |  NULL    |
|      477 | 254        |  NULL    |
|      478 | 286        |  NULL    |
|      479 | 286        |  FREE    |
|      480 | 286        |  FREE    |
|      481 | 401        |  FREE    |
|      482 | 401        |  1       |
|      483 | 401        |  FREE    |
|      484 | 405        |  NULL   |
|      485 | 405        |  1       |
|      486 | 405        |  5       |
|      487 | 405        |  FREE    |
|      488 | 406        |  1       |
|      489 | 406        |  5       |
|      490 | 406        |  5       |
|      491 | 406        |  2       |
|      ... | ...        |  ...     |
+----------+------------+----------+

Expected result

Constraint :

i would like to get all the foreignkey id that have not all trainer NULL or FREE (at least 1 but can be 2 or more) but at least one should be NULL

+------------+-------+
|    ID_TR   | FIELD |
+------------+-------+
|      405   |   ..  |
+------------+-------+

i dont know how to do it in mysql ? Group then HAVING one trainer == FREE OR NULL ?

thanks for helping me

4

3 回答 3

1

这听起来像是EXISTS运营商的经典用例:

SELECT *
FROM   mytable a
WHERE  EXISTS (SELECT 1
               FROM   mytable b
               WHERE  a.foreignkey = b.foreignkey 
               AND    trainer IS NOT NULL 
               AND    trainer <> 'FREE'

编辑:
如果您只想要不同foreignkey的 s:

SELECT DISTINCT foreignkey
FROM   mytable a
WHERE  EXISTS (SELECT 1
               FROM   mytable b
               WHERE  a.foreignkey = b.foreignkey 
               AND    trainer IS NOT NULL 
               AND    trainer <> 'FREE'
于 2014-01-26T12:53:30.357 回答
0
SELECT   t.*
FROM     my_table    t
    JOIN cross_table x ON x.FOREIGNKEY = t.ID_TR
WHERE    x.TRAINER IS NOT NULL
     AND x.TRAINER <> 'FREE'
GROUP BY t.ID_TR
于 2014-01-26T12:52:09.617 回答
0

您可以计算是的数字,'FREE'然后NULL执行逻辑:

select foreignkey,
       sum(trainer is null) as NumNulls,
       sum(trainer = 'Free') as NumFrees,
       count(*) as Num
from table t
group by foreignkey

然后你想添加一个有子句来得到你想要的。我不确定这到底是什么意思:“我想获得所有外键 id 不是所有的 trainer NULL 或 FREE(至少 1 个,但可以是 2 个或更多),但至少一个应该是 NULL”。

例如,这可能是您想要的:

having NumNulls > 0 and NumFrees > 0

或者这个:

having NumNulls > 0 and NumFrees > 0 and cnt >= 2;
于 2014-01-26T13:27:47.243 回答