gpt4 book ai didi

MySQL:返回另一个表中不存在相关条目的字段

转载 作者:行者123 更新时间:2023-11-29 01:18:52 27 4
gpt4 key购买 nike

首先,对标题感到抱歉,因为我不是以英语为母语的人,这很难表达。换句话说,我想要实现的是:

  • 我正在尝试从表 virtual_domains 中获取所有域名,而在 virtual_aliases 表中没有以“postmaster@%”开头的相应条目。

所以如果我有两个域:

foo.org
example.org

他们有这样的别名:

info@foo.org       => admin@foo.org
postmaster@foo.org => user1@foo.org
info@example.org => admin@example.org

我希望查询仅返回域“foo.org”,因为“example.org”缺少邮件管理员别名。

这是表格布局:

mysql> show columns from virtual_aliases;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| domain_id | int(11) | NO | MUL | NULL | |
| source | varchar(100) | NO | | NULL | |
| destination | varchar(100) | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+

mysql> show columns from virtual_domains;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+

我尝试了很多小时的 IF、CASE、LIKE 查询,但都没有成功。我不需要最终解决方案,也许只是一些解释的提示。谢谢!

最佳答案

SELECT * FROM virtual_domains AS domains
LEFT JOIN virtual_aliases AS aliases
ON domains.id = aliases.domain_id
WHERE aliases.domain_id IS NULL

LEFT JOIN 返回“左”表中的所有记录,即使它们在“右”表中没有对应的记录。这些记录会将正确的表字段设置为 NULL。使用 WHERE 去除所有其他的。


我想我第一次没有正确理解你的意思。对于单个域,您在 aliases 中有多个条目,并且您希望仅显示那些在别名表中没有以“postmaster”开头的条目的域?

在这种情况下,您应该像这样使用 NOT IN:

SELECT * FROM virtual_domains AS domains
WHERE domains.id NOT IN (
SELECT domain_id
FROM virtual_aliases
WHERE whatever_column LIKE "postmaster@%"
)

关于MySQL:返回另一个表中不存在相关条目的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4712495/

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