Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a field in a table reference to another table in MySQL/MariaDB?

Tags:

mysql

Say I'm setting up an small database with just 2 tables: feeds and feeditems.

In one table I'd store the feedname and url, with an ID as unique key.

In the second table I'd like to store some info coming from feed items (in example: date, title, url of the item and feedname). But instead of storing the feed name, I'd like to reference this feed field to the ID of that feed in the first table.

Thanks

like image 659
versvs Avatar asked Feb 17 '23 15:02

versvs


1 Answers

this a quick example of how to achieve your requirement...

CREATE TABLE IF NOT EXISTS `feeds` (
  `Feed_ID` int(11) NOT NULL,
  `Feed_Name` varchar(32) NOT NULL,
  `Feed_Url` varchar(255) NOT NULL,
  PRIMARY KEY (`Feed_ID`)
)

CREATE TABLE IF NOT EXISTS `feeditems` (
  `FeedItem_ID` int(11) NOT NULL,
  `Feed_ID` int(11) NOT NULL,
  `FeedItem_Date` datetime NOT NULL,
  `FeedItem_Title` varchar(255) NOT NULL,
  `FeedItem_Url` varchar(255) NOT NULL,
  `FeedItem_Name` varchar(255) NOT NULL,
  PRIMARY KEY (`FeedItem_ID`),
  FOREIGN KEY (`Feed_ID`) REFERENCES `feeds`(`Feed_ID`)
                      ON DELETE CASCADE
)
like image 146
MrSimpleMind Avatar answered Feb 20 '23 13:02

MrSimpleMind