Quantcast
Channel: User Mohamed Mufeed - Stack Overflow
Viewing all articles
Browse latest Browse all 36

Answer by Mohamed Mufeed for How to link two tables using foreign key under certain conditions in SQL?

$
0
0

I think your are misunderstanding the basics here. Creating a table is one thing and interacting(Creating, Reading, Updating and Deleting data) with it is a different thing.

Lets assume that you have your products table's structure like this for example.

CREATE TABLE products (     item_no INT PRIMARY KEY,     item VARCHAR(20) NOT NULL ,     qty SMALLINT UNSIGNED NOT NULL ,     price DECIMAL(8,2) NOT NULL ,     status ENUM('SOLD','UNSOLD') NOT NULL);

To link this to your what-ever table (in this case links), You just do.

CREATE TABLE links(    s_no             INT PRIMARY KEY,    product_item_no  INT NOT NULL,    FOREIGN KEY ( product_item_no )         REFERENCES products ( item_no )         ON UPDATE CASCADE         ON DELETE RESTRICT);

notice there is no need for the status because it can be fetched from the products table by joining the two tables.

for example by issuing a select query at a later point in time.

eg.

SELECT l.*, p.status FROM links l    LEFT JOIN products p ON p.item_no = l.product_item_noWHERE p.status = 'SOLD';

Viewing all articles
Browse latest Browse all 36

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>