2012-01-26 51 views
1

我的查詢從MySQL DB中選擇任務。每個任務都有一個組ID,如果組等於0,則它是一個我只希望返回的私人任務,如果任務來自運行此查詢的用戶。希望是有道理的:-)MySQL:如果在哪裏?

SELECT t.id, t.title, t.created_by, u.username 
FROM (p_tasks AS t) 
LEFT JOIN p_groups AS g ON t.group_id = g.id 
JOIN p_users AS u ON t.assigned_to_user_id = u.id 
WHERE 
(
    t.assigned_to_user_id = $user_id OR 
    t.owner_user_id = $user_id 
) 
AND 
(
    g.priority >= '10' OR 
    t.group_id = 0 
) 
AND 
(
    t.status != "approved" AND 
    t.status != "closed" 
) 
ORDER BY c.name 

我只能爲那些創建任務的人返回group_id = 0的任務嗎?

回答

0

我不完全understud你的意思,但像在英語中,清晰的語法是:

where 
(... AND ... AND ...) 
or 
(... AND ... AND ...) 
or 
(... AND ... AND ...) 
1
(group_id <> 0 OR t.owner_user_id = $user_id) AND 
t.assigned_to_user_id = $user_id AND 
t.status <> "approved" AND 
t.status <> "closed" 

您應該能夠建立你的where子句不使用IF語句。

1

不知道我完全理解您的查詢,但您描述的部分看起來像這樣。這假設你想要所有的公共任務和所有分配給用戶或用戶擁有的私人任務。

WHERE 
( 
    (t.assigned_to_user_id = $user_id OR t.owner_user_id = $user_id) AND 
    t.group_id = 0 
) 
OR 
( 
    t.group_id != 0  
) 
0
SELECT t.id, t.title, t.created_by, u.username 
FROM (p_tasks AS t) 
LEFT JOIN p_groups AS g ON t.group_id = g.id 
JOIN p_users AS u ON t.assigned_to_user_id = u.id 
WHERE 
(
    t.assigned_to_user_id = $user_id OR 
    t.owner_user_id = $user_id 
) 
AND 
(
    g.priority >= '10' OR 
    t.group_id = 0 
) 
AND 
(
    t.status != "approved" AND 
    t.status != "closed" 
) 
AND 
(
    (
      t.group_id <> 0 
    ) 
    OR 
    (
    t.created_by = $user_id 
    ) 
) 

ORDER BY c.name 
0

感謝所有!我想我知道它。

當我刪除t.group_id = 0這似乎是我想要的:-) 如果我是我通過owner_user_idassigned_to_user_id選擇任務的所有者。如果我不是,那麼任務是否是私人的(group_id = 0)並不重要,因爲我沒有足夠的權限來選擇/查看它。

明天我會試試。

再次感謝您的幫助!