Multiple tables in one view? - mysql

Today my question is how would I go about creating a view in a MySQL database that uses more than two tables?
Here is my query (it works) I am not looking to change my current query, mostly looking for a nice reference with examples on this topic.
CREATE OR REPLACE VIEW vw_itemsPurchased AS
SELECT `tbl_buyers`.`fldPrimaryKey` as fldFKeyBuyer, `tbl_buyers`.`fldEmail` as fldBuyerEmail, `tbl_buyers`.`fldAddressStreet`, `tbl_buyers`.`fldAddressCity`, `tbl_buyers`.`fldAddressState`, `tbl_buyers`.`fldAddressZip`, `tbl_buyers`.`fldAddressCountry`, `fldPaymentCurrency`, `fldPaymentGross`, `fldPaymentStatus`, `fldReceiverEmail`, `fldTransactionId`
FROM `tbl_transactions` INNER JOIN `tbl_buyers`
ON `tbl_transactions`.`fldFKeyBuyer` = `tbl_buyers`.`fldPrimaryKey`
Thanks for your time!

To use more than two tables, you simply continue adding JOIN statements to connect foreign keys. Adapting your code to add an imaginary third table tbl_products might look like this:
CREATE OR REPLACE VIEW vw_itemsPurchased AS (
SELECT
tbl_buyers.fldPrimaryKey as fldFKeyBuyer,
tbl_buyers.fldEmail as fldBuyerEmail,
tbl_buyers.fldAddressStreet,
tbl_buyers.fldAddressCity,
tbl_buyers.fldAddressState,
tbl_buyers.fldAddressZip,
tbl_buyers.fldAddressCountry,
fldPaymentCurrency, fldPaymentGross,
fldPaymentStatus,
fldReceiverEmail,
fldTransactionId,
tbl_tproducts.prodid
FROM
tbl_transactions
INNER JOIN tbl_buyers ON tbl_transactions.fldFKeyBuyer = tbl_buyers.fldP
-- Just add more JOINs like the first one..
JOIN tbl_products ON tbl_products.prodid = tbl_transactions.prodid
In the above method, the first and second tables relate, and the first and third tables relate. If you have to relate table1->table2 and table2->table3, list multiple tables in the FROM and relate them in the WHERE. The below is just for illustration and doesn't make much sense, as you probably wouldn't have a customer id in the same table as a product price.
SELECT
t1.productid,
t2.price,
t3.custid
FROM t1, t2, t3
WHERE
-- Relationships are defined here...
t1.productid = t2.productid
AND t2.custid = t3.custid

Related

Selecting/Inserting data between 3 tables

I think there are something wrong with my structure. I have 3 tables in the database. I want to show all the supply in a specific division. I did some trial and errors but I can't insert another supply in the same plan id. I wanted to add more supplies in one of specific division / specific plan id.Here's my query to select the supplies.
SELECT
division.acronym,
supply.`name`,
supply.unit,
supply.supply_id,
supply.price,
supply.estimated_budget,
supply.quantity
FROM
division
INNER JOIN plan ON plan.plan_id = division.division_id
INNER JOIN supply ON supply.supply_id = plan.plan_id
The table is only available at documentation. So, I insert my ERD diagram as an image.
ERD edited
I think you should put division_id and supply_id to plan table as FOREIGN KEYS to join all three tables.
Then your query should look like:
division
INNER JOIN plan ON plan.division_id=division.division_id
INNER JOIN supply ON supply.supply_id=plan.supply_id

comparing two table columns in mysql results in duplicate

I have two tables, I've been trying to print the result from each but they are being duplicated. These are the two MySQL tables and the result. Notice the duplication.
The sql code for the project is:
SELECT * FROM savings,savtype WHERE cust_id=".$_SESSION['user']
I'm also looking for a work around this, in the meantime, id appreciate any assistance on this.
because you are not specifying how the two tables are related. You need to add that, either via an explicit ... JOIN ... (USING|ON)
SELECT
*
FROM
savings JOIN savtype USING (savtype_id)
WHERE
cust_id = ".$_SESSION['user']
or by providing the criteria in the where clause.
SELECT
*
FROM
savings, savtype
WHERE
savings.savtype_id = savtype.savtype_id AND
cust_id = ".$_SESSION['user']
As I understand from the screenshot you added, it makes joint between those tables, and what you probably want it left join from savings and savtype tables.
SELECT *
FROM `savings`
LEFT JOIN `savtype`
ON savings.savtype_id=savtype.savtype_id
where cust_id=".$_SESSION['user'] .";
Update if this did the trick,
You can learn more about left join here: https://www.w3schools.com/sql/sql_join_left.asp

Query to join 3 tables

I need to write a query to join 3 tables.
My tables are:
ucommerce_customer
ucommerce_order
ucommerce_order_line
All 3 tables have a column called order_id.
The table ucommerce_order has a column called order_status.
When the order_status is set to "open" I want to display the order details.
ResultSet myRs = myStmt.executeQuery
("SELECT * FROM ucommerce_customer
INNER JOIN ucommerce_order
INNER JOIN ucommerce_order_line
WHERE ucommerce_order.order_status = 'open'");
My query ignores the order status and displays all orders, open and closed.
Also I have several products so ucommerce_order_line has several entries for the same order_id, my query displays duplicate entries and it duplicates the entire list as well.
How can I write a query that will show only open orders without duplicating everything?
In MySQL, the on/using clause is optional. This is very sad because someone can make mistakes like you did. Your question only mentions one column, so perhaps that is all that is needed for the join:
SELECT *
FROM ucommerce_customer INNER JOIN
ucommerce_order
USING (orderId) INNER JOIN
ucommerce_order_line
USING (OrderId)
WHERE ucommerce_order.order_status = 'open';
I would be surprised if the customer table really had a column called OrderId (seems like a bad idea in most situations), so the first USING clause might want to use CustomerId.
I would recommend to use a natural join instead. Maybe that's where the errors are coming from.
The duplicates can be removed by running SELECT DISTINCT * ...

Inner join of same table with conditions

So my problem is as follow, I have a table in MySQL with a UserId column and an ObjectId column (its a many to many relationship), and what I would like is to have is a query that gives me the list of objects that user X and Y share. Not sure how to make the joins to make this happen.
Use query something like below using self join
Select columns from table t1 join table t2 on t1.objectid=t2.objectid where t1.userid=X and t2.userid=Y

How can i update a table based on a count of another table while using LIKE statement

I know how to update one table's field from another table's count using t1.id=t2.id etc.. but i have somewhat typical issue. I have to use LIKE STATEMENT in WHERE clause.
This is something similar i wanted to do.
UPDATE `CATEGORIES`
SET `num_listings` = (SELECT COUNT(*)
FROM `LISTINGS`
WHERE `LISTINGS`.`CATEGORY` LIKE
ws_concat('', "%-", `CATEGORIES`.`ID`, "-%"));
(Example: I have CATEGORY stored as -25- in the LISTINGS table as a field name CATEGORY)
I understand that i cannot use ws_contact here but is there another way to achieve it?
Thanks in advance.
Unless there is a good reason for the category ID to be represented only by a part of a string in the listings table, the best way to handle such a structure of data is to add a category_id column to the LISTINGS table, and make sure that when adding or editing a listing this column is populated properly.
This would allow to simply JOIN the two tables ON categories.id = listings.category_id and makes much more sense. This would also give better performance by far.
If you do want to keep the DB structure as is, you can use a temporary table, with LIKE and CONCAT:
DROP TABLE IF EXISTS temp;
CREATE TABLE temp AS
SELECT categories.id, COUNT(*) AS c
FROM categories
JOIN listings ON listings.category LIKE CONCAT('%',categories.id,'%')
GROUP BY categories.id;
UPDATE categories, temp
SET categories.num_listings = temp.c
WHERE categories.id = temp.id;