繁体   English   中英

从一个表中获取有关所有行的信息,而在联接表中该行不是

[英]Get information about all rows from one table, when in join table that row is not

如果在表userItems中没有记录与moduleItems只是null联接的情况下,如何获取?

SELECT `users`.*, `useritems`.*, `moduleitems`.*, `modulesubitems`.* FROM `users`
LEFT JOIN `useritems` ON useritems.f_user_id = users.user_id
LEFT JOIN `moduleitems` ON moduleitems.moduleItem_id = useritems.f_moduleItem_id
LEFT JOIN `modulesubitems` ON modulesubitems.modulesubitem_id = useritems.userItem_value

编辑: 我的数据库结构

CREATE TABLE IF NOT EXISTS `moduleitems` (
`moduleItem_id` int(11) NOT NULL AUTO_INCREMENT,
`f_module_id` int(11) NOT NULL,
PRIMARY KEY (`moduleItem_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=63 ;

CREATE TABLE IF NOT EXISTS `modules` (
`module_id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`module_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

CREATE TABLE IF NOT EXISTS `modulesubitems` (
`moduleSubitem_id` int(11) NOT NULL AUTO_INCREMENT,
`f_moduleItem_id` int(11) NOT NULL,
PRIMARY KEY (`moduleSubitem_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=19 ;

CREATE TABLE IF NOT EXISTS `useritems` (
`f_user_id` int(11) NOT NULL,
`f_moduleItem_id` int(11) NOT NULL,
`userItem_value` varchar(255) DEFAULT NULL,
PRIMARY KEY (`f_user_id`,`f_moduleItem_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=35 ;

如果您希望查看每个用户的每个模块项,无论他们在useritems表中是否有匹配的记录,这都应该起作用:

SELECT  `users`.*, `useritems`.*, `moduleitems`.*, `modulesubitems`.* 

FROM    `users`

        CROSS JOIN `moduleitems`

        LEFT JOIN `useritems` 
        ON useritems.f_user_id = users.user_id
        AND moduleitems.moduleItem_id = useritems.f_moduleItem_id

        LEFT JOIN `modulesubitems` 
        ON modulesubitems.modulesubitem_id = useritems.userItem_value

如果尝试查找不在联接表中的所有记录(使用LEFT JOIN时),请添加到WHERE子句中,该表中要联接的字段为NULL。 如果没有匹配项,则联接表中的所有字段均为NULL。

例如,如果您试图在moduleitems表中查找不匹配的情况,这将起作用:

SELECT `users`.*, `useritems`.*, `moduleitems`.*, `modulesubitems`.* 
FROM `users`
LEFT JOIN `useritems` ON useritems.f_user_id = users.user_id
LEFT JOIN `moduleitems` ON moduleitems.moduleItem_id = useritems.f_moduleItem_id
LEFT JOIN `modulesubitems` ON modulesubitems.modulesubitem_id = useritems.userItem_value
WHERE moduleitems.moduleItem_id IS NULL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM