简体   繁体   中英

Foreign key constraint makes SELECT query return 0 rows

I've been given this database structure:

DROP TABLE IF EXISTS `account`;
CREATE TABLE IF NOT EXISTS `account` (
  `accountType` varchar(120) NOT NULL,
  PRIMARY KEY (`accountType`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `username`;
CREATE TABLE IF NOT EXISTS `username` (
  `usernameID` int(11) NOT NULL AUTO_INCREMENT,
  `password` varchar(200) NOT NULL,
  `name` varchar(200) NOT NULL,
  `phoneNr` int(15) NOT NULL,
  `email` varchar(120) NOT NULL,
  `accountType` varchar(120) NOT NULL,
  PRIMARY KEY (`usernameID`),
  KEY `accountType` (`accountType`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `username`
  ADD CONSTRAINT `username_ibfk_1` FOREIGN KEY (`accountType`) REFERENCES `account` (`accountType`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;

Now, I want to SELECT a user from the username table. In MySQL workbench I get the results I'm looking for with:

SELECT name FROM username;

However, when using a mysqli query in PHP i get num_rows => 0 in my result object, like this:

(The var_dump above the result object is the query I'm sending in)

It works if I remove the KEY from the username table, so I assume that's where the problem lies. How should I alter my SELECT query?

I believe name is a reserved word in MySQL. You may just need to escape it using the backtick character like so,

SELECT `name` FROM username;

See Keywords and Reserved Words .

For some reason it seems like InnoDB was the issue. As soon as I removed ENGINE=InnoDB from the username table, everything worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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