Mysql SQL高级选择语句
Mysql SQL高级选择语句,mysql,sql,left-join,Mysql,Sql,Left Join,我需要为当前word和id\u translation选择所有translations,但如果行中referer=1(当前user),则我不需要其他结果(translations来自当前word的其他用户),如果没有referer=1,全部展示 users_translations +---------+----------------+----------+---------+ | id_user | id_translation | referrer | id_word | +-------
我需要为当前
word
和id\u translation
选择所有translations
,但如果行中referer=1
(当前user
),则我不需要其他结果(translations
来自当前word
的其他用户),如果没有referer=1
,全部展示
users_translations
+---------+----------------+----------+---------+
| id_user | id_translation | referrer | id_word |
+---------+----------------+----------+---------+
| 1 | 17 | 1 | 4 |
| 2 | 17 | 2 | 4 |
| 3 | 18 | NULL | 4 |
第一行不需要,因为我们有tuser=1
。当没有tuser=1
时,应返回所有结果
我不知道如何构建select语句,如果有人告诉我如何使其工作,我将非常感激。首先想到的是
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 |
--将其添加到where子句中
id\u用户抱歉,无法准确理解您想要什么。为什么有两个referers列?什么是t.id?在querytranslations和users_translations具有相同结构的情况下,表翻译只包含唯一的翻译,但users_translations允许为不同的单词添加相同的翻译。我试图避免重复条目,但这并不重要,因为问题在查询中,并且在返回的结果中。t是translations table的简称,但对于用户来说,t是translations table,你给了我一个思考的食物。我稍后会检查这是否有效。谢谢
users_translations
+---------+----------------+----------+---------+
| id_user | id_translation | referrer | id_word |
+---------+----------------+----------+---------+
| 1 | 17 | 1 | 4 |
| 2 | 17 | 2 | 4 |
| 3 | 18 | NULL | 4 |
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 |
--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