Accessing two tables, having a relationships/PK and FK


This article will show you on how to get a data with one or more entities/table are involve. ok let’s do the basic. Given that we have table of products and table of sales and with this respective contents when we want to view all of the products that can be sold we can use this SQL statement:

 

    
     Select *
                From tbl_products

                The keyword select is used to instruct on what are the specific fields/attributes to be shown  when this statement is executed, the * symbol indicates that you want to select  all the fields on that table but if you want to select/get a specific column you will just need to specify on what is the name of that column separated by comma if it is multiple fields.

                Select fld_PID,fld_ProductName
                From tbl_Products

                The “from” clause is used to specify on what is the name of table you want to access multiple tables can be declared on the from clause separating it by comma.

                Select *
                From tbl_Sales, tbl_products

                This select statement will just show the following results:
 


                If you observe the result it just select the two tables and merge it and repeated the content we don’t like this result hmmmm so what do we want to do?, we want to see on what are the products which are already sold.  Using the where clause we can use a certain query to show it.
Select tbl_Products.fld_PID, tbl_Products.fld_productname, tbl_Sales.fld_Quantity,tbl_Sales.fld_Date
From tbl_Products,tbl_Sales
Where tbl_Products.fld_PID = tbl_Sales.fld_PID

               
                That is an example of selecting one record to another table. There are more basic way in selecting a record from two table or more, using what we call the inner join and outer join , but for this simple purpose of demonstration you can use this way of selecting a record, take note that where clause is used to select a record with specific criteria or condition.
                If you want to access a field using two table u need to specify the name of the table then put a dot after that the name of the field, tbl_Products.fld_productname to make your statement shorter you can use some technique called Alias.

                NOTE: if you already read the article of creating a recordset to your vb6 project you can put this statement on the rst.open part.

Happy coding

Walang komento:

Mag-post ng isang Komento