嘿伙计们我想学习如何从多个数据库查询到多个数据库。这是一个包含三个表和一个多个表和三个外键的数据库的示例。 如何在st_glowne_others
表上执行SELECT语句?
例如,如果我想从'st_components'表中选择所有可能的结果, 它与'st_glowne'表中名称列的特定值相关联, 和'st_pages'表中名称列的specyfic值。 提前致谢!。
TABLE1
CREATE TABLE `st_glowne` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`location` varchar(50) COLLATE utf8_polish_ci NOT NULL DEFAULT './',
PRIMARY KEY (`name`),
KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci
TABLE2
CREATE TABLE `st_pages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`filelocation` varchar(50) COLLATE utf8_polish_ci NOT NULL DEFAULT 'pages/',
PRIMARY KEY (`name`),
KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_polish_c
表3
CREATE TABLE `st_components` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`location` varchar(100) COLLATE utf8_polish_ci NOT NULL DEFAULT 'components/',
PRIMARY KEY (`name`),
KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci
这是我们要查询的表:
CREATE TABLE `st_glowne_others` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`st_glowne` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`st_pages` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`st_components` varchar(50) COLLATE utf8_polish_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`),
KEY `st_glowne` (`st_glowne`),
KEY `st_pages` (`st_pages`),
KEY `st_components` (`st_components`),
KEY `st_components_2` (`st_components`),
CONSTRAINT `st_glowne_others_ibfk_3` FOREIGN KEY (`st_components`) REFERENCES `st_components` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `st_glowne_others_ibfk_1` FOREIGN KEY (`st_glowne`) REFERENCES `st_glowne` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `st_glowne_others_ibfk_2` FOREIGN KEY (`st_pages`) REFERENCES `st_pages` (`name`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci
你能告诉我如何从中查询吗?很多人感谢!
答案 0 :(得分:2)
最简单的方法是加入:
SELECT * FROM `st_glowne_others` go
LEFT JOIN `st_glowne` ON `st_glowne`.name = go.st_glowne
LEFT JOIN `st_pages` ON `st_pages`.name = go.st_pages
LEFT JOIN `st_components` ON `st_components`.name = go.st_components
但是,我建议您重新考虑您的架构 - 是否有任何理由让PK成为名称字段?您有一个AUTO INCREMENT
id列,这是一种更加标准的方式来连接两个表。
例如(对于每个表格):
CREATE TABLE `st_glowne` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_polish_ci NOT NULL,
`location` varchar(50) COLLATE utf8_polish_ci NOT NULL DEFAULT './',
PRIMARY KEY (`id`),
)
然后使用您的st_glowne_others
表,引用ID列。
CREATE TABLE `st_glowne_others` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`st_glowne_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `st_glowne_id` (`st_glowne_id`),
CONSTRAINT `st_glowne_others_ibfk_3` FOREIGN KEY (`st_glowne_id`) REFERENCES `st_glowne` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
)