我有两个表,一个帐户表和一个暂停表。而不是首先在登录时检索他们的信息,然后再检查一个主动暂停的另一个查询,是否可以加入两个查询并检查两个查询?
如果用户没有活动暂停,此查询当前不返回任何行,我不希望这样做。我希望它为suspension
表字段返回一个空结果,然后返回所有信息。
SELECT `account`.`username`, `suspension`.`user_id` FROM `account`,`suspension` WHERE `account`.`user_id` = 5 OR `suspension`.`user_id` = 5
那将返回0结果。如果没有suspension
部分,它将返回用户的用户名。我希望它返回用户名,并为该字段提供空的suspension.user_id
或0
,如果可能的话:
username => Test,
user_id => 0
CREATE TABLE `account` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(12) NOT NULL,
`password` char(32) NOT NULL,
`email_address` varchar(250) NOT NULL,
`creation_date` int(11) unsigned NOT NULL,
`creation_ip` varchar(25) NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `username` (`username`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `suspension` (
`user_id` int(10) unsigned NOT NULL,
`suspension_reason` tinyint(1) NOT NULL DEFAULT '0',
`suspension_date` int(10) unsigned NOT NULL,
`suspension_expire` int(10) unsigned NOT NULL,
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
答案 0 :(得分:0)
您希望使用Mysql Join将两个表连接在一起,引用用户ID。
帐户表
CREATE TABLE `account` (
`id` INT UNSIGNED AUTO_INCREMENT,
`username` VARCHAR(10) NOT NULL,
PRIMARY KEY(`id`)
);
暂停表
CREATE TABLE `suspension` (
`user_id` INT UNSIGNED DEFAULT NULL,
FOREIGN KEY (`user_id`) REFERENCES account(`id`) ON DELETE CASCADE ON UPDATE CASCADE
);
查询
SELECT A.username, A.id FROM `account` AS A
LEFT JOIN `suspension` AS S ON S.user_id = A.id
WHERE A.id = 5 AND S.user_id IS NULL;
如果用户出现在Suspension中,则不会返回任何结果。如果用户未被暂停,则返回用户结果。要返回用户及其暂停状态,您可以使用以下查询。
SELECT A.username, A.id, (S.user_id IS NOT NULL) AS `suspended` FROM `account` AS A
LEFT JOIN `suspension` AS S ON S.user_id = A.id
WHERE A.id = 5;