MySQL:连接两个表/如果表 A 中的特定字段不为空,则读取表 B 中特定行的所有数据


MySQL: Joining two tables / Read all data from specific row in table B if specific field in table A is not empty

https://i.stack.imgur.com/ZRH9c.jpg(请参阅数据库结构的示例图像)

大家好

我正在尝试在两个以特定字母开头的表中搜索单词,但我不知道如何进行正确的连接。

如果在"user_vocabulary"中没有给出voc_id,我想从user_vocabulary中获取单词,但如果有voc_id我想从"system_vocabulary"读取所有数据,其中user_vocabulary.voc_id=system.vocabulary.id。

我只用来读取一个表(仅供您参考): 从user_vocabulary中选择 *,其中单词如"$user_input%"按单词 ASC 排序

我发现了一些或多或少相似的帖子,但似乎无法将它们转换为此问题。

任何帮助都非常感谢。干杯汤姆

您希望

user_vocabulary.wordsystem_vocabulary.word中获取的值最终位于输出的同一列中。 您可以使用IF函数执行此操作:

SELECT
  uv.id,
  IF(uv.voc_id = 0,uv.word,sv.word) AS WORD
FROM user_vocabulary uv
LEFT JOIN system_vocabulary sv
ON (uv.voc_id = sv.id)
HAVING word LIKE '%user_input%'
+------+-------+
| id   | word  |
+------+-------+
|    1 | hat   |
|    2 | home  |
|    3 | hello |
+------+-------+
3 rows in set (0.00 sec)

试试这个

SELECT *
FROM user_vocabulary
left join system_vocabulary
on system_vocabulary.voc_id = user_vocabulary.id
WHERE user_vocabulary.word LIKE '%$user_input%' or system_vocabulary.word like     '%$user_input%'
ORDER BY word ASC

编辑

另一种方式

SELECT *
FROM user_vocabulary as uv
, system_vocabulary as sv
WHERE uv.word LIKE '%$user_input%'
or sv.word like '%$user_input%'

这应该根据您的要求工作:

SELECT user_vocabulary.id,
   COALESCE(system_vocabulary.word, user_vocabulary.word) word
FROM user_vocabulary
LEFT JOIN system_vocabulary
   ON system_vocabulary.id = voc_id AND voc_id <> 0