gpt4 book ai didi

MYSQL查询返回空结果

转载 作者:行者123 更新时间:2023-11-29 02:02:03 25 4
gpt4 key购买 nike

我需要查找用户的电子邮件首选项。

此表包含用户可以接收的电子邮件类型,按类别分割。

email_preferences_categories

+----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | text | YES | | NULL | |
| overview | text | YES | | NULL | |
+----------+------------------+------+-----+---------+----------------+

此表包含他们对接收各种类型的偏好。如果他们没有设置他们的偏好,这个表将不会有任何行给他们。

email_preferences

+------------+---------------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| user_id | int(10) unsigned | NO | | NULL | |
| name | text | YES | | NULL | |
| frequency | enum('Daily','Monthly','None') | YES | | Daily | |
+------------+---------------------------------+------+-----+---------+----------------+

我需要构建一个 MYSQL 查询,该查询返回与给定用户的电子邮件首选项相对应的名称和频率。

SELECT name, frequency
FROM email_preferences
LEFT JOIN email_preferences_categories using (name)
WHERE user_id = 42

我遇到问题的地方:如果用户没有设置他们的偏好,这个查询不会返回任何行。我希望它为缺少的电子邮件类别返回默认值“每日”。

最佳答案

LEFT JOIN 更改为 RIGHT JOIN

...
FROM email_preferences
RIGHT JOIN email_preferences_categories
...

或者您可以交换表格:

...
FROM email_preferences_categories
LEFT JOIN email_preferences
...

这两个选项都做同样的事情 - 确保您从 email_preferences_categories 中获取所有行,即使在 email_preferences 中没有匹配的行也是如此。

您还需要更改您已经注意到的连接条件。


I would like it to return the default of 'Daily' for email categories that are missing.

您可以使用 IFNULL :

SELECT name, IFNULL(frequency, 'Daily') AS frequency

关于MYSQL查询返回空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13124279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com