我的数据库中有两个表,其结构如下
已启用应用
CREATE TABLE `applications_enabled` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`application_id` int(11) DEFAULT NULL,
`organization_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `application_id` (`application_id`),
KEY `organization_id` (`organization_id`),
CONSTRAINT `applications_enabled_ibfk_1` FOREIGN KEY (`application_id`) REFERENCES `applications` (`id`),
CONSTRAINT `applications_enabled_ibfk_2` FOREIGN KEY (`organization_id`) REFERENCES `user` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
申请清单
CREATE TABLE `applications` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`is_public` tinyint(1) DEFAULT '0',
`content` text COLLATE utf8mb4_unicode_ci,
`logo` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`namespace` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
现在,organization
启用了应用程序,如applications_enabled
数据库所示,参考organization_id
和application_id
已启用。
我想要的是单个查询,列出applications
表中列出的所有应用程序,如果某个组织已启用或未启用,则列出字段集。
我到目前为止的当前sql查询是
SELECT
*
FROM applications
LEFT JOIN applications_enabled
ON applications.id = applications_enabled.application_id
WHERE applications_enabled.organization_id = 89
OR applications_enabled.organization_id IS NULL;
我在测试时工作正常,但随后我注意到,由于我们有更多数据,如果另一个organization
已启用application
,则organization_id
未设置为{{ 1}}并且NULL
丢失了。什么是正确的SQL查询?
答案 0 :(得分:1)
如果你按照每个组织获得这个列表,那么我建议你走另一条路。首先检查所有的applications_enabled,然后将这些结果与实际应用程序连接:
SELECT
*
FROM
applications_enabled
INNER JOIN
applications ON applications_enabled.application_id = applications.id
WHERE
applications_enabled.organization_id = 89;