Mysql: Duplicate and incorrect output when using join - php

I have 4 tables on which I need to use a join. The query is returning duplicate rows. However for simplicity I will post my question with just 2 tables as the problem still exits even with 2 tables. Tables are called as product_offer and promo. The structures are as below
product_offer table:
id product_id offer_id store_id validity
1 1 1 1 2016-12-12 00:00:00
2 2 2 1 2016-12-12 00:00:00
3 3 3 1 2016-12-12 00:00:00
4 1 4 1 2016-12-12 00:00:00
promo table:
id product_id store_id name
1 1 1 Buy 1 Get 1 free
2 2 1 10% off
3 3 1 $10 off
4 1 1 Get Chips Free
I am trying to fetch all the offers for a particular product-store combination. I am expecting to get this
product_id offer_id store_id name
1 1 1 Buy 1 Get 1 Free
1 4 1 Get Chips Free
But When I run this query I am getting the below output which is incorrect and with duplicate rows
SELECT po.product_id, po.offer_id,po.store_id,o.name
from product_offer po
left join promo o on po.product_id = o.product_id
where po.product_id = 1 and po.store_id = 1
product_id offer_id store_id name
1 1 1 Buy 1 Get 1 Free
1 4 1 Buy 1 Get 1 Free
1 1 1 Get Chips Free
1 4 1 Get Chips Free
I also want to improve the query and use concat(using ~ as separator) to only return one row per product_id as below:
product_id offer_id store_id name
1 1~4 1 Buy 1 Get 1 free~Get Chips Free

You want to use a GROUP BY, what does it, it takes the column you chose puts them together to avoid duplicate results where data in that column matches
SELECT po.product_id, po.offer_id,po.store_id,o.name
from product_offer po
left join promo o on po.product_id = o.product_id
where po.product_id = 1 and po.store_id = 1
GROUP BY product_id
In order to concatenate them, there is the option of GROUP_CONCAT, you can read more at http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

use Group by with GROUP_CONCAT
SELECT po.product_id,GROUP_CONCAT(DISTINCT po.offer_id SEPARATOR '~') offer_id
,po.store_id,GROUP_CONCAT(DISTINCT o.name SEPARATOR '~') name
from product_offer po
left join promo o on po.product_id = o.product_id
where po.product_id = 1 and po.store_id = 1
Group by product_id

I realized I was doing the Join ON the wrong column. When I changed the join on offer_id from product_offer and id on promo it worked nicely.
SELECT po.product_id, group_concat(po.offer_id SEPARATOR '~') offer_id, po.store_id ,group_concat(o.name SEPARATOR '~') offer
FROM product_offer po
LEFT JOIN
promo o ON po.offer_id = o.id
WHERE
po.product_id = 1 and po.store_id = 1

I think you need to group by offer_id
SELECT po.product_id,GROUP_CONCAT(po.offer_id SEPARATOR '~') offer_id,po.store_id,o.name
from product_offer po
left join promo o on po.product_id = o.product_id
where po.product_id = 1 and po.store_id = 1
Group by offer_id

Related

Mysql join two tables with sum of quantity

Q : I am trouble to do following task in mysql query.
Task is get all products (If product is duplicate than sum of it's qty) and deduct wastage stock (If wastage product is duplicate than sum of it's qty).
I have two tables like,
1) manage_stock
2) manage_wastage
manage_stock
=> This table has p_id(Product ID) and many rows with product duplication's.
p_id p_name p_qty
1 Pro-1 10
2 Pro-2 15
3 Pro-3 8
1 Pro-1 15
manage_wastage
=> This table has p_id(Product ID) of manage_stock table. It is also many rows with product duplication's.
p_id w_qty
1 2
1 4
3 5
Desired Output
p_id p_name p_qty w_qty final_qty
1 Pro-1 20 6 14
2 Pro-2 15 0 15
3 Pro-3 8 5 3
Thank you very much.
You just have to compute the difference between the stock quantity and the wastage
SELECT s.p_id, s.p_name, SUM(p_qty), SUM(w_qty), SUM(p_qty) - SUM(w_qty) as final_qty
FROM manage_stock s
LEFT OUTER JOIN manage_wastage w
ON s.p_id = w.p_id
GROUP BY s.p_id, s.p_name
try this one
SELECT s.p_id, s.p_name, SUM(p_qty),SUM(ifnull(w_qty, 0)),SUM(p_qty - ifnull(w_qty, 0)) as total
FROM manage_stock s
left outer JOIN manage_wastage w
ON s.p_id = w.p_id
GROUP BY s.p_name
its work
SELECT ms.p_id ,GROUP_CONCAT(ms.p_name)p_name ,SUM(ms.p_qty) p_qty ,SUM(mw.w_qty) w_qty,SUM(ms.p_qty)-SUM(mw.w_qty) final_qty FROM manage_stock ms
INNER JOIN manage_wastage mw on ms.p_id =mw.p_id
GROUP BY ms.p_id
Try above code.
As p_name always unique with p_id GROUP_CONCAT() only returns single name.

How to count a Column data using join over 3 tables

I have three tables
tbl_product
item_id | item_name
company_details
v_id | item_id | company_name
user_ratings
r_id | rate | v_id
I want to count the rate and also get the rate of the company. Here is my query
SELECT company_details.v_id,
company_details.company_name,
COUNT(user_ratings.rate) as vote,
user_ratings.rate,
tbl_product.item_name
FROM company_details
LEFT JOIN tbl_product ON tbl_product.item_id = company_details.item_id
LEFT JOIN user_ratings ON user_ratings.v_id = company_details.v_id
GROUP BY company_details.v_id, user_ratings.rate
This is Whts i am Getting after this query:
v_id company_name vote rate item_name
1 The Oberoi Udaivilas 1 4 5 Star Hotels
1 The Oberoi Udaivilas 1 5 5 Star Hotels
2 The Taj Mahal Palace 2 5 4 Star Hotels
3 Rambagh Palace 1 5 3 Star Hotels
4 Taj Lake Palace 1 5 5 Star Hotels
5 Windflower Hall 1 3 2 Star Hotels
5 Windflower Hall 1 5 2 Star Hotels
6 Leela Palace Kempinski 0 n 4 Star Hotels
7 Umaid Bhawan Palace 0 n 4 Star Hotels
8 Hotel Ratan Vilas 0 n 4 Star Hotels
9 The Leela Palace 0 n 4 Star Hotels
10 The Imperial Hotel 0 n 3 Star Hotels
You can see vote column is not counting.
This is what I am expecting
v_id company_name vote rate item_name
1 The Oberoi Udaivilas 2 5 5 Star Hotels
2 The Taj Mahal Palace 2 5 4 Star Hotels
But this query is not counting the rate from user_ratings table, because of I also want to get the rate, if I remove the user_ratings.rate from select clause, then this query works, but when I add the user_ratings.rate in the select clause, then this query is not counting the rates as(vote), and it is returning as one rows in every count.
You should remove user_ratings.rate from group by clause and add tbl_product.item_name.
SELECT
company_details.v_id,
company_details.company_name,
tbl_product.item_name,
COUNT(user_ratings.rate) as vote,
avg(user_ratings.rate) as rate
FROM
company_details
LEFT JOIN tbl_product ON tbl_product.item_id = company_details.item_id
LEFT JOIN user_ratings ON user_ratings.v_id = company_details.v_id
GROUP BY company_details.v_id, company_details.company_name, tbl_product.item_name;
Seems to me that your query is only missing an aggregation on the rate column, and from the expected output I'd say it's a max. You also should fix your group by. Try this one
SELECT company_details.v_id,
company_details.company_name,
COUNT(user_ratings.rate) as vote,
MAX(user_ratings.rate) as rate,
tbl_product.item_name
FROM company_details
LEFT JOIN tbl_product ON tbl_product.item_id = company_details.item_id
LEFT JOIN user_ratings ON user_ratings.v_id = company_details.v_id
GROUP BY company_details.v_id,
company_details.company_name,
tbl_product.item_name
Query and result are both correct. Look at the rate
you can try this query it will return your exactly output according to your given 3 tables.
"select c.v_id , c.company_name , u.rate , p.item_name from company_details c join tbl_product p on p.item_id = c.item_id join user_details u on c.v_id = u.v_id group by c.company_name ";

Get sum of min values in each group from Mysql

I am trying to retrieve the minimum price of some models.
Each model belongs to a certain group which belongs to a product.
I have the following tables:
Product
model_id product_id price
1 1 100
2 1 120
3 1 100
4 1 200
5 1 250
10 1 20
11 1 50
12 1 50
Product Overview
model_id product_id group_id
1 1 A
2 1 A
3 1 A
4 1 A
5 1 A
10 1 B
11 1 B
12 1 B
Product Group Optional
group_id product_id
B 1
Some groups could be optional, which means price will be zero unless the member wants to choose otherwise.
So in the example above, I want to get the sum of minimum price from each group.
We have two groups, group A and group B.
Group A minimum price value is 100 (model_id 1 and 3)
Group B minimum price value is 20 (model_id 10) but because Group B is optional then that means minimum price value is 0.
Overall sum of min values: 100 (Group A) + 0 (Group B) = 100
My code so far:
SELECT po.group_id,
CASE WHEN
((SELECT COUNT(*) FROM product_group_optional pgo
WHERE po.group_id = group_id AND po.product_id = 1 AND po.product_id = product_id) >= 1)
THEN SUM(0)
ELSE SUM(p.price)
END AS sum_price
FROM product_overview po, product p
WHERE po.product_id = 1
AND po.model_id = p.model_id
AND p.price = (
SELECT MIN(p2.price)
FROM product p2, product_overview po2
WHERE po2.product_id = 1 AND po2.group_id = po.group_id
AND po2.model_id = p2.model_id
)
GROUP BY po.group_id
The output:
group_id sum_price
A 200
B 0
The problem is that I get 200 for Group A but it should be 100.
There are 2 models with min value 100, model 1 and 3. And I assume these are sum together = 100 + 100 = 200.
Issue a) But I want to just take the min value, no matter how many times this value exists.
Issue b) Also, I am trying to get the SUM of those two output SUM of Group A and Group B.
But I am not sure how to do it.
I want it to be done in this query.
Desired output
Sum of all groups
100
Can anyone lead me to the right direction please?
You can use the following query:
SELECT SUM(min_price)
FROM (
SELECT po.group_id,
MIN(CASE WHEN pgo.group_id IS NULL THEN price ELSE 0 END) AS min_price
FROM Product AS p
INNER JOIN Product_overview AS po
ON p.product_id = po.product_id AND p.model_id = po.model_id
LEFT JOIN Product_group_optional AS pgo ON po.group_id = pgo.group_id
GROUP BY po.group_id) AS t
I'm not sure that I understand the keys of your tables, and the problem as well.
There is few questions.
a) The answer should be 120?
b) If the Product has no price, the is price null?
c) If there is a Product in a group with null price and others with price, should it be counted as 0?
Here is how you could get the sum of the lower prices of each group, ignoring the product_group_optional for while:
SELECT t2.group_id, sum(t2.new_price)
FROM
(
SELECT t.group_id, t.new_price
FROM
(
SELECT po.group_id, if(ifnull(pgo.product_id, true), p.price, 0) as new_price
FROM product p, product_overview po
LEFT JOIN product_group_optional pgo ON po.group_id = pgo.group_id
WHERE p.model_id = po.model_id
ORDER by po.group_id, new_price
) t
GROUP BY t.group_id
) t2

mysql join and sum problems

Im having some trouble with this.
Here's an example of my tables.
Booking
id zone_id name excursion_id
1 2 1
2 1 1
3 2 1
The table where I have the quantities
booking_price
id_booking id_price quantity
1 1 2
1 2 3
2 1 1
2 2 0
3 1 2
3 2 3
Here the zone table
Zone
id Name
1 a
2 b
3 c
So I want to have a table like that
Zone_id Quantity
1 1
2 10
3 0
The problem is when im joining tables and filtering by excursion_id im not getting ALL the zones.
I want to know how many people goes in each zone.
I think better way of doing it is
select z.id, coalesce(sum(bp.quantity),0) as quantity
from Booking b
right join Zone z on z.id = b.zone_id AND b.excursion_id = 1
left join booking_price bp on bp.id_booking = b.id
group by z.id
demo http://sqlfiddle.com/#!2/771f5/13
You could use a query like:
SELECT zone.id as zone_id,
sum(quantity) as Quantity
FROM zone
LEFT JOIN Booking on Booking.zone_id = zone.id
LEFT JOIN Excursion on Excursion.id_booking = Booking.id
GROUP BY zone.id

Help with limiting a joined mysql database query

I have written a query which returns all records with some many-to-many joins correctly for the entire set or an individual article using WHERE a.id = ?
SELECT a.id, date_added, title, content, category_id, person_id, organization_id, c.name AS category_name, firstname, lastname, o.name AS organization_name
FROM articles AS a
LEFT OUTER JOIN articles_categories AS ac ON a.id=ac.article_id
LEFT OUTER JOIN categories AS c ON c.id=ac.category_id
LEFT OUTER JOIN articles_people AS ap ON a.id=ap.article_id
LEFT OUTER JOIN people AS p ON p.id=ap.person_id
LEFT OUTER JOIN articles_organizations AS ao ON a.id=ao.article_id
LEFT OUTER JOIN organizations AS o ON o.id=ao.organization_id
ORDER BY date_added
BUT!
I've hit a brick wall trying to work out how to limit the articles to a specific number of IDs, for working with pagination.
I'm ideally trying to use as simple and clear SQL statements as possible because I'm using the codeigniter framework with their active record class.
http://codeigniter.com/user_guide/database/active_record.html
Would really appreciate some help as I don't want to revert to using multiple queries for this as I've tried to reduce it down to a single query for database efficiency.
Have search around and tried some alternatives but nothing seems to work. Many thanks!
For example the results I return are like this
---------------------------------------------------------------------
id title category_id person_id organization_id
---------------------------------------------------------------------
1 test 1 1 1
1 test 2 1 1
1 test 1 2 1
1 test 1 1 2
1 test 5 1 1
1 test 8 1 1
1 test 1 4 1
1 test 1 4 2
1 test 1 1 1
2 test 2 2 1 1
2 test 2 1 2 1
2 test 2 1 1 2
2 test 2 5 1 1
2 test 2 8 1 1
2 test 2 1 4 1
2 test 2 1 4 2
I need the results like this so that I can create sub-arrays in the php like this:
$articles = $query->result_array();
$output = array();
foreach ($articles as $article) {
// set up article details
$article_id = $article['id'];
// add article details
$output[$article_id]['article_id'] = $article_id;
$output[$article_id]['date_added'] = $article['date_added'];
$output[$article_id]['title'] = $article['title'];
$output[$article_id]['content'] = $article['content'];
// set up people details and add people array with details if exists
if (isset($article['person_id'])) {
$person_id = $article['person_id'];
$output[$article_id]['people'][$person_id]['person_id'] = $person_id;
$output[$article_id]['people'][$person_id]['lastname'] = $article['lastname'];
$output[$article_id]['people'][$person_id]['firstname'] = $article['firstname'];
}
// set up organizations details and add organizations array with details if exists
if (isset($article['organization_id'])) {
$organization_id = $article['organization_id'];
$output[$article_id]['organizations'][$organization_id]['organization_id'] = $organization_id;
$output[$article_id]['organizations'][$organization_id]['organization_name'] = $article['organization_name'];
}
// set up categories details and add categories array with details if exists
if (isset($article['category_id'])) {
$category_id = $article['category_id'];
$output[$article_id]['categories'][$category_id]['category_id'] = $category_id;
$output[$article_id]['categories'][$category_id]['category_name'] = $article['category_name'];
}
}
But if I just use LIMIT (with offset etc) 1
the results I get are
---------------------------------------------------------------------
id title category_id person_id organization_id
---------------------------------------------------------------------
1 test 1 1 1
instead of
---------------------------------------------------------------------
id title category_id person_id organization_id
---------------------------------------------------------------------
1 test 1 1 1
1 test 2 1 1
1 test 1 2 1
1 test 1 1 2
1 test 5 1 1
1 test 8 1 1
1 test 1 4 1
1 test 1 4 2
1 test 1 1 1
which is my desired result.
OK, so finally I worked out how it is possible.
Thought i'd include it here in case anyone else has the same problem.
Changing this line
FROM articles AS a
to this
FROM (SELECT * FROM articles LIMIT 5,3) AS a
does what I wanted.
So, why don't you use OFFSET 0,10 and LIMIT *number_of_results* in the SQL Query? (if I understood the question)
Specific number of IDs... WHERE ID IN (2,4,6,8)... ?
Are you using codeigniter's pagination?
http://codeigniter.com/user_guide/libraries/pagination.html
You can easily limit the number of records that are being returned using the MySQL LIMIT clause. This can be achieved like the following with your sample query.
SELECT a.id, date_added, title, content, category_id, person_id, organization_id, c.name AS category_name, firstname, lastname, o.name AS organization_name
FROM articles AS a
LEFT OUTER JOIN articles_categories AS ac ON a.id=ac.article_id LEFT OUTER JOIN categories AS c ON c.id=ac.category_id
LEFT OUTER JOIN articles_people AS ap ON a.id=ap.article_id LEFT OUTER JOIN people AS p ON p.id=ap.person_id
LEFT OUTER JOIN articles_organizations AS ao ON a.id=ao.article_id LEFT OUTER JOIN organizations AS o ON o.id=ao.organization_id
ORDER BY date_added
LIMIT 10
Where 10 is the number of records you wish to display. The MySQL LIMIT clause allows you to specify a limit of the number of records and an initial offset. Like so:
LIMIT <offset>,<limit>
In your case <offset> would be the current page * the number of records on a page. <limit> would be the number of records you would like to display per page.

Categories