2
translations
+---------+----------------+----------+---------+
| id_user | id_translation | referrer | id_word |
+---------+----------------+----------+---------+
|       1 |              3 |     NULL |       4 |
|       1 |             17 |     NULL |       3 |
|       2 |             17 |     NULL |       5 |
|       2 |             17 |     NULL |       1 |
|       2 |             17 |     NULL |       7 |


words
+----+------+
| id | word |
+----+------+
|  4 | out  |
+----+------+


users_translations
+---------+----------------+----------+---------+
| id_user | id_translation | referrer | id_word |
+---------+----------------+----------+---------+
|       1 |             17 |     1    |       4 |
|       2 |             17 |     2    |       4 |
|       3 |             18 |     NULL |       4 |

我需要translations为当前word和选择全部id_translation,但如果在行中referrer = 1(当前user),那么我不需要另一个结果(translations来自其他用户的当前word),如果没有referrer = 1,则显示全部。

SELECT DISTINCT `t`.*, `ut`.`id_user` AS tuser 
FROM translations AS t
LEFT JOIN users_translations AS ut ON `t`.`id` = `ut`.`id_translation`
INNER JOIN words ON `words`.`id` = `ut`.`id_word` OR `words`.`id` = `t`.`id_word`
WHERE (`word` = 'help')
ORDER BY `t`.`translation` ASC


+----+-------------+---------+---------+-------+
| id | translation | id_word | id_user | tuser |
+----+-------------+---------+---------+-------+
| 17 | допомагати  |       4 |       1 |     2 |
| 17 | допомагати  |       4 |       1 |     1 |

第一行不需要,因为我们有tuser = 1. 如果没有tuser = 1,则应返回所有结果。

我不明白如何构建 select 语句,我将非常感谢有人向我展示如何使其工作。

4

1 回答 1

1

首先想到的

--add this to your where clause
    id_user <= 
        CASE WHEN EXISTS(SELECT * FROM translations WHERE id_user = 1 AND id_word = words.id_word) 
        THEN 1 
        ELSE (SELECT MAX(Id) FROM translations)
        END
于 2013-09-13T06:36:53.687 回答