我是sql的初学者。 我有两个表用户和分期付款
CREATE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) NOT NULL,
`password` varchar(10) NOT NULL,
`father_name` varchar(20) NOT NULL,
`phone` varchar(20) NOT NULL,
`cnic` varchar(20) NOT NULL,
`email` varchar(100) NOT NULL,
`address` varchar(100) NOT NULL,
`introducer` varchar(100) NOT NULL,
`date` date DEFAULT NULL,
`reg_number` varchar(100) DEFAULT NULL,
`installment` int(100) NOT NULL,
`user_level` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `cnic` (`cnic`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
INSERT INTO `users` (`id`, `user_name`, `password`, `father_name`, `phone`, `cnic`, `email`, `address`, `introducer`, `date`, `reg_number`, `installment`, `user_level`) VALUES
(2, 'qaser', 'Qaser1', 'zamarrud', '0312546879', '37406-3140185-1', 'tariq_kareem@yahoo.com', 'street # 6', 'rizwan', '2014-08-20', 'E-002', 3000, 0);
和
CREATE `installments` (
`installment_id` int(11) NOT NULL AUTO_INCREMENT,
`month` date DEFAULT NULL,
`prv_arrear` int(100) NOT NULL,
`amount` int(100) NOT NULL,
`total` int(100) NOT NULL,
`receive` int(100) NOT NULL,
`arrear` int(100) NOT NULL,
`fk_users_id` int(11) NOT NULL,
PRIMARY KEY (`installment_id`),
KEY `fk_users_id` (`fk_users_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
INSERT INTO `installments` (`installment_id`, `month`, `prv_arrear`, `amount`, `total`, `receive`, `arrear`) VALUES
(2, '2014-08-20', 2000, 2500, 4500, 3000, 1500);
当我运行以下查询时,我正确获得了第一个表的记录,但第二个表的记录显示了NULL值
SELECT * FROM users
LEFT JOIN installments
ON users.id=installments.installment_id
WHERE users.cnic='37406-3140185-1';
上述查询中是否缺少任何内容,或者是否有其他方法同时从两个表中获取记录
id user_name password father_name phone cnic email address introducer date reg_number installment user_level installment_id month prv_arrear amount total receive arrear fk_users_id
2 qaser Qaser1 zamarrud 0312546879 37406-3140185-1 tariq_kareem@yahoo.com street # 6 rizwan 2014-08-20 s-001 3000 0 NULL NULL NULL NULL NULL NULL NULL NULL
我还使用以下查询插入记录以获取主键值并插入外键
INSERT INTO `installments`(`id`, `month`, `prv_arrear`, `amount`, `total`, `receive`, `arrear`, fk_users_id)
SELECT NULL,now(),1000,2500,3500,3000,500, id
FROM users
WHERE cnic = '37406-3140190-1'
请提前帮助我,如果我的问题出现问题,请对不起,因为我是sql的新手。
答案 0 :(得分:2)
我怀疑正确的加入条件是fk_users_id
。所以这可能会做你想要的:
SELECT *
FROM users u LEFT JOIN
installments i
ON u.id = i.fk_users_id
WHERE u.cnic = '37406-3140185-1';