how to join 2 tables in SQL - php

I need to join my variants table to my products table so that I am able to get the product_id from both tables, how can I put this into my existing query..?
I've tried to add it not working.
$query = query("
SELECT *
FROM products
FULL OUTER
JOIN variants WHERE product_id=" . escape_string($_GET['add']). " ");

It sounds like you are looking for an inner join, not a full outer join. You'll also want to specify the column you are joining both tables on:
$query = query("
SELECT *
FROM products
JOIN variants ON variants.product_id = products.product_id
WHERE products.product_id =" . escape_string($_GET['add']). " ");
*Note: I'm assuming product_id is a column on both the variants and products table. If, for example, the product_id of products is just id, you'll want to change the join condition to:
ON variants.product_id = products.id

Related

I want to use JOIN for a query and I want to show only the name of the product with the image

I'm practicing with queries and I have a question about JOIN.
I have these 2 tables:
**PRODUCTS**:
id
name
description
**PRODUCT_IMAGES**
id
product_id
image_link
And I want to use JOIN to combine these 2 table where I only want to see the name of the product with the specific image that is linked with the id.
I try to to that with this QUERY:
SELECT * FROM `product_images`
LEFT JOIN `products`
ON `product_images`.`products.id` = `products`.`id`;
The problem now is that I get all the information, but I only want to see the name and the image.
You have an error with product_images.id as it should be like "product_images.product_id" , I fixed this, kindly use this query.
SELECT products.name, product_images.image_link FROM `product_images`
INNER JOIN `products`
ON `product_images`.`product_id` = `products`.`id`;
Change * to name, image_link:
SELECT name, image_link FROM `product_images`
LEFT JOIN `products`
ON `product_images`.`products.id` = `products`.`id`;
SELECT products.id,products.name FROM `product_images`
LEFT JOIN `products`
ON `product_images`.`products.id` = `products`.`id`;
Instead of * you can give the column names comma separated.
You may choose LEFT JOIN or INNER JOIN as per your need.
Select the desired columns in the select statement. It's a best practice to name the table and column together. Otherwise if a column exists with the same name in both tables it will throw an error.
SELECT `products`.`name`,`product_images`.`image_link`
FROM `product_images`
LEFT JOIN `products`
ON `product_images`.`products.id` = `products`.`id`;
Simple use inner join
SELECT
p.name,
i.image_link
FROM
products p
JOIN
product_images i USING(product_id)
If you are sure, you have data in both tables then use the below
SELECT P.name, PI.image_link FROM product_images PI
inner JOIN products P
ON P.id = PI.product_id
If you are sure you have data in product table but might be not in product_image then use below
SELECT P.name, PI.image_link FROM products P
left JOIN product_images PI
ON P.id = PI.product_id

Limit values for the left Join part of a query

Please i have four tables joined together using the LEFT JOIN, the images table is linked to the items table by img_item, thus each item can have more images. i want to fetch only the first image of every item. How do i go achieve this.
SELECT * FROM items
LEFT JOIN category ON items.item_cat = category.cat_id
LEFT JOIN users ON users.user_id=items.item_user
LEFT JOIN institutions ON institutions.inst_id=users.user_inst
LEFT JOIN images ON images.img_item = items.item_id
ORDER BY item_id DESC
In MySQL, you can enumerate the results using variables, and then choose the first. Another alternative is to identify which one you want, and choose that one. The following chooses the image with the largest id:
SELECT *
FROM items LEFT JOIN
category
ON items.item_cat = category.cat_id LEFT JOIN
users
ON users.user_id=items.item_user LEFT JOIN
institutions
ON institutions.inst_id = users.user_inst LEFT JOIN
images
ON images.img_item = items.item_id AND
images.img_id = (SELECT MAX(i2.img_id)
FROM images i2
WHERE i2.img_item = images.img_item
);
ORDER BY item_id DESC

MYSQL Query Calculation in relationship

MySQL Schema
product_categories:
id, name
products
id,category_id,name,description
product_offers
id,product_id,name,email
product_offer_negotiations
id,product_offer_id,offer(float),by_user(ENUM-Seller/buyer),status
This is there query i have tried...
select products.*,
product_categories.name as category_name,
COUNT(product_offers.id) AS total_offers,
ROUND( AVG(product_offer_negotiations.offer), 2) AS avg_offer
from products
inner join product_categories on product_categories.id = products.category_id
inner join product_offers on product_offers.product_id = products.id
inner join product_offer_negotiations on product_offer_negotiations.product_offer_id = product_offers.id
and product_offer_negotiations.by_user = ?
group by products.id;
I would like to get all fields from product table, total_offers and avg_offer offer for product (only highest value from negotiation table per offer_id - no duplicatation)
This query only returns first row of products table. Thanks for help.

Mysql GROUP BY or DISTINCT query usage in PHP

I'm a little bit confused about these kind of new query types for me (DISTINCT,GROUP BY etc.)
I have three tables in my database.
BRANDS
PRODUCTS
RECIPES
What I would like to do is to list BRANDS then look for PRODUCTS of that brand and look if there is a RECIPE of those products, then I want it to be written.
I'm able to write it with the basic queries;
$sql = "SELECT * FROM BRANDS";
$sql2 = "SELECT * FROM PRODUCTS WHERE BRANDID = 1";
$sql3 = "SELECT * FROM RECIPES WHERE PRODUCTID = 2";
but it repeats the brands.As far as I googled I have to use GROUP BY or DISTINCT in my query.
How should I create my query layout and which of them I should use?
Thank you.
I don't think you necessarily need to do all the distinct and grouping, unless your database has duplicate rows. You can select all of that in one query like so:
Select Brands.BrandId, Brands.BrandName, Products.ProductId, Products.ProductName, Recipes.*
From Brands
Inner Join Products On Products.BrandId = Brands.BrandId
Inner Join Recipes On Recipes.ProductId = Products.ProductId
Where
Brands.BrandId = 1 And
Products.ProductId = 2
Order By Brands.BrandId, Products.ProductId, Recipes.RecipeId
Please note that I assumed you have a Brands.BrandName and Products.ProductName column. This query will get you a complete recordset, filtered based on Brand and Product.

mysql join getting a value or a null into a column

I am very new to SQL, so I am having a couple problems figuring things out. The database is for an online store, and the structure is something like this:
users: UserID, UserName, etc.
pricelists: PricelistID, UserID, ProductItemID, Price
productitems: ProductItemID, ProductID, ItemID
products: ProductID, ManufacturerID, WebPageText, etc.
Each product can have one or more items (e.g. if the product page is selling T-shirts, there may be 5 different T-shirt variations for sale). That's pretty normal. What's not normal is that the pricing for each item is determined by what's in the user's pricelist, because each user is assigned particular pricing. Not all users have a price assigned for every item.
Here is the question: The requirement from management is that the user should be able to see every product, even if that product is not in the user's pricelist. If the user has no pricelist entry for a productitem, the page should display, "Contact us for pricing." I have not been able to figure out how to do this with one query. Every join that I attempted involving the pricelist table threw out products for which the user didn't have a price assigned. I am given only the ProductID and UserID. I have put my code below, which is a mix of mysql and PHP. It works, but it is clunky, especially seeing as I have to redo the second query over and over. Please tell me how I really ought to be doing it.
$query_product = sprintf("SELECT * , (items.Stock - (SELECT Coalesce(Sum(DetailQuantity),0)
FROM orderdetails
INNER JOIN orders ON OrderID = DetailOrderID
INNER JOIN productitems ON orderdetails.ProductItemID = productitems.ProductItemID
INNER JOIN products ON productitems.ProductID = products.ProductID
INNER JOIN items ON productitems.ItemID = items.ItemID
WHERE OrderDate > ProductUpdateDate))*ProductLive
AS NumLeft
FROM productitems
INNER JOIN products ON products.ProductID = productitems.ProductID
JOIN items ON productitems.ItemID = items.ItemID
WHERE products.ProductID = %s",GetSQLValueString($ProductID, "int"));
$product = mysql_query($query_products, $x) or die(mysql_error());
$row_product = mysql_fetch_assoc($product);
//after narrowing down to one productitem, either through user selections or while looping through $row_product:
$query_price = sprintf("SELECT Price FROM pricelists
WHERE UserID = %s AND ProductItemID = %s", GetSQLValueString($UserID, "int"), GetSQLValueString($row_product['ProductItemID'], 'int'));
$price = mysql_query($query_price, $x) or die(mysql_error());
$row_price = mysql_fetch_assoc($price);
$row_product['Price'] = $row_price['Price'];
Later in the code, I check whether $row_products['Price'] is empty or not to determine what is displayed on the page.
EDIT: I thought this would be obvious, but ... I have to limit pricelists by WHERE UserID = %s. That means I can't just tack on a LEFT JOIN pricelists ON pricelists.ProductItemID = productitems.ProductItemID, which was actually the first thing I tried, and which does not work. Limiting the outer join in the WHERE statement turns it into an inner join.
Add the pricelists table as an LEFT join to your main query:
SELECT field1, field2, ..., pl.*
FROM orderdetails
INNER JOIN orders ON OrderID = DetailOrderID
...
LEFT JOIN pricelists pl PN pl.ProductItemID = productitems.ProductItemID
..
In your code check if the price in the pricelists table is null, if so, show the text.
You should look into using an outer join for this. Heres a great description of the difference between an inner and outer join -> inner join vs outer join

Categories