开发者

Database design MySQL using foreign keys

I'm having some a little trouble understanding how to hand开发者_如何学编程le the database end of a program I'm making. I'm using an ORM in Kohana, but am hoping that a generalized understanding of how to solve this issue will lead me to an answer with the ORM.

I'm writing a program for users to manage their stock research information. My tables are basically like so:

CREATE TABLE tags(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
tags VARCHAR(30),
UNIQUE(tags)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;


CREATE TABLE stock_tags(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
tag_id INT NOT NULL,
stock_id INT NOT NULL,
FOREIGN KEY (tag_id) REFERENCES tags(id),
FOREIGN KEY(stock_id) REFERENCES stocks(id) ON DELETE CASCADE
)
ENGINE=INNODB DEFAULT CHARSET=utf8;


CREATE TABLE notes(
id INT AUTO_INCREMENT NOT NULL,
stock_id INT NOT NULL,
notes TEXT NOT NULL,
FOREIGN KEY (stock_id) REFERENCES stocks(id) ON DELETE CASCADE,
PRIMARY KEY(id)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;


CREATE TABLE links(
id INT AUTO_INCREMENT NOT NULL,
stock_id INT NOT NULL,
links VARCHAR(2083) NOT NULL,
FOREIGN KEY (stock_id) REFERENCES stocks(id) ON DELETE CASCADE,
PRIMARY KEY(id) 
)
ENGINE=INNODB DEFAULT CHARSET=utf8;

How would I get all the attributes of a single stock, including its links, notes, and tags? Do I have to add links, notes, and tags columns to the stocks table and then how do you call it? I know this differs using an ORM and I'd assume that I can use join tables in SQL.

Thanks for any help, this will really help me understand the issue a lot better.


You will have to link the tables together using JOINS

Something like

SELECT  *
FROM    stocks s INNER JOIN
        stock_tags st ON s.id = st.stock_id INNER JOIN
        tags t ON st.tag_id = t.id etc...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜