Get rows with matching values in column in same table - mysql

I have the following DDLs...
CREATE TABLE IF NOT EXISTS `product` (
`id_product` int(10),
`id_manufacturer` int(10)
);
INSERT INTO `product` (`id_product`, `id_manufacturer`) VALUES
(1,1),
(2,1),
(3,2),
(4,1),
(5,2);
CREATE TABLE IF NOT EXISTS `feature_product` (
`id_feature` int(10),
`id_product` int(10),
`id_feature_value` int(10)
);
INSERT INTO `feature_product` (`id_feature`, `id_product`, `id_feature_value`) VALUES
(5, 1, 9),
(5, 2, 9),
(5, 3, 10),
(5, 4, 10),
(7, 5, 10);
http://sqlfiddle.com/#!2/cbe05/1/0
Can you explain me please, how I can get - all Products with the same Manufacturer and the same Feature_value?
Now (in project) I do it with 2 additional SELECT's (for getting id_manufacturer and id_feature_value), but maybe there are more correct (and fast) way?
Thanks for your time and sorry for my English)
I need too see result like this:
id_product |
-----------|
1 |
2 |
only this 2 products have same manufacturer and (at the same time) same feature value

Just use GROUP_CONCAT:
SELECT GROUP_CONCAT(p.id_product SEPARATOR '\n') AS Products
FROM product p
INNER JOIN feature_product fp ON (p.id_product = fp.id_product AND fp.id_feature = 5)
GROUP BY p.id_manufacturer, fp.id_feature_value
HAVING COUNT(p.id_manufacturer) > 1
AND COUNT(fp.id_feature_value)>1;
This will give you the list of Products having multiple Manufacturer Id and Feature Value in a single line, separated by a newline character. You can change the separator as your requirement.
Here is the SQL Fiddle link:
http://sqlfiddle.com/#!2/cbe05/70

Related

Unexpected LEFT JOIN behavior with condition in ON clause

I have the following three tables:
fees - has information about a fee on a bill
payments - has information about payments on a bill (including payments to fees)
details - has detailed information about the payment
I'm struggling to understand why my query isn't returning the result I expect.
SQL Fiddle: sqlfiddle.com/#!9/942636/3
CREATE TABLE fees (
receipt_number int(11) NOT NULL,
bill_number int(11) NOT NULL,
version int(11) NOT NULL,
fee_id int(11) NOT NULL,
fee_type varchar(30) NOT NULL
);
CREATE TABLE payments (
receipt_number int(11) NOT NULL,
bill_number int(11) NOT NULL,
version int(11) NOT NULL,
payment_id int(11) NOT NULL,
amount decimal(13,2) NOT NULL DEFAULT '0.00'
);
CREATE TABLE details (
receipt_number int(11) NOT NULL,
payment_id int(11) NOT NULL,
fee_type varchar(30) DEFAULT NULL
amount decimal(13,2) NOT NULL DEFAULT '0.00'
);
INSERT INTO fees (receipt_number, bill_number, version, fee_id, fee_type)
VALUES (111, 100, 1, 1, 'a'),
(111, 100, 1, 1, 'b'),
(111, 100, 1, 2, 'c'),
(111, 100, 1, 2, 'd');
INSERT INTO payments (receipt_number, bill_number, version, payment_id, amount)
VALUES (111, 100, 1, 98, 30.00),
(111, 100, 1, 99, 60.00);
INSERT INTO details (receipt_number, payment_id, fee_type, amount)
VALUES (111, 98, 'a', 10.00),
(111, 98, 'b', 10.00),
(111, 98, 'd', 10.00),
(111, 99, 'a', 20.00),
(111, 99, 'b', 20.00),
(111, 99, 'c', 20.00);
I'm attempting to find out if:
A bill has a fee with type 'c'
There is a payment made towards that fee (determined by the fee_type)
My query:
SELECT fees.bill_number, details.receipt_number AS has_payment_type_c
FROM fees
LEFT JOIN payments
USING (bill_number, version)
LEFT JOIN details
ON details.receipt_number = payments.receipt_number
AND details.payment_id = payments.payment_id
AND details.fee_type = 'c'
WHERE fees.fee_type = 'c'
AND details.receipt_number IS NULL;
I get the result:
bill_number has_payment_type_c
100 (null)
I should not see the bill_number in this list, as the bill has a fee and a payment towards that fee.
I am filtering the details.fee_type in the ON clause to both reduce the number of records looked up in that table and to only join to that table for that specific fee_type. The query seems to "work" (0 results) by moving the fee_type join condition to the WHERE clause, but I don't think that is correct.
My questions:
What am I doing wrong in my query? How can I fix it to produce the result I'm looking for, and how does that fix work?
Assuming I get a working query, can I just simply reverse the table order and the SELECT to find the opposite information - payments of a certain fee_type without an associated fee record of that same type?
The answer is to use a derived table that inner joins payments and details, and then left join the derived table to fees:
SELECT DISTINCT fees.bill_number, fees.version, x.bill_number AS has_payment_type_c
FROM fees
LEFT JOIN (
SELECT payments.bill_number, payments.version, details.fee_type
FROM payments
JOIN details
USING(receipt_number, payment_id)
WHERE details.fee_type = 'c'
) x
ON fees.bill_number = x.bill_number
AND fees.version = x.version
WHERE fees.fee_type = 'c'
AND x.bill_number IS NULL;
This will return the expected 0 results, and can be validated by removing the where condition that checks for a null x.bill_number:
bill_number version has_payment_type_c
100 1 100
The same approach works for finding payments without a fee. Use a derived table that inner joins payments and details, then left join to fees. SELECT the fee.bill_number AS has_payment_type_c and add WHERE fee.bill_number IS NULL to the WHERE clause.

How to count multiple columns grouping by rows in MySQL?

I have two tables, "keywords" and "stats" and want to know per keyword how many results each merchant has. So one row per keyword.
Desired result e.g.:
KWD | RESULTS Amazon | RESULTS eBay
test 3 5
second 6 2
The tables:
create table keywords
(
ID mediumint unsigned auto_increment
primary key,
KEYWORD varchar(255) null
);
create table stats
(
MERCHANT_ID tinyint unsigned not null,
TYPE_ID mediumint unsigned not null comment 'the ID of the coresponding type. E.g. kw_id from keywords',
RESULTS smallint unsigned null,
DATE date not null,
primary key (DATE, MERCHANT_ID, TYPE_ID)
)
comment 'How many results does each merchant have per search?';
Sample data:
-- keywords
insert into test.keywords (ID, KEYWORD) values (1, 'testing');
insert into test.keywords (ID, KEYWORD) values (2, 'blablub');
-- stats
insert into test.stats (MERCHANT_ID, TYPE_ID, RESULTS, DATE) values (1, 1, 33, '2021-07-06');
insert into test.stats (MERCHANT_ID, TYPE_ID, RESULTS, DATE) values (1, 2, 3, '2021-07-06');
insert into test.stats (MERCHANT_ID, TYPE_ID, RESULTS, DATE) values (2, 1, 22, '2021-07-06');
insert into test.stats (MERCHANT_ID, TYPE_ID, RESULTS, DATE) values (2, 2, 6, '2021-07-06');
The query:
select
kwd.KEYWORD,
mss.MERCHANT_ID,
mss.RESULTS
from keywords kwd
LEFT JOIN stats mss ON mss.TYPE_ID = kwd.ID
where
date = 20210705
group by kwd.ID
There are about 10 merchants. Is it possible to get one row per keyword and have the number of results per merchant in seperate colunns?
Try something like this:
select
kwd.KEYWORD,
SUM(IF(mss.MERCHANT_ID = 'amazon', mss.RESULTS, 0)) as `amazon_sum`,
SUM(IF(mss.MERCHANT_ID = 'eBay', mss.RESULTS, 0)) as `eBay_sum`
from keywords kwd
LEFT JOIN stats mss ON mss.TYPE_ID = kwd.ID
where
date = 20210705
group by kwd.ID

SQL Product Group Size & Colors Together

I have following 3 tables, which I want to use to group 2 rows together to make it as single row, because they belong to one product.
Order
--------
order_id
Order_product
-------------
order_id
order_product_id
order_product_attribute
------------------------------
orders_products_attributes_id
order_id
product_id
products_options
options_id
=== Data ===
|1|2|7|Size |1|270
|2|2|7|Colour(s) |3|99202
|3|2|8|Size |1|270
|4|2|8|Colour(s) |3|47768
My desire result needs to be following:
order_id, product_id, size_options_id (option_id for size), colour_options_id (option_id for color)
size_options_id is optional, which means it might not even exist for some products.
I'm not sure what join I need to use to get this result in one go, rather then doing it from PHP checks.
Assuming that your tables are as follows:
create table order (order_id int);
insert into order values(2);
create table order_product (order_id int, order_product_id int);
insert into order_product values (2,7);
insert into order_product values (2,8);
create table order_product_attribute (orders_products_attributes_id int, order_id int, product_id int, products_options int, options_id int);
insert into order_product_attribute values (1, 2, 7, 1, 270);
insert into order_product_attribute values (2, 2, 7, 3, 99202);
insert into order_product_attribute values (3, 2, 8, 1, 270);
insert into order_product_attribute values (4, 2, 8, 3, 47768);
desired output:
2 7 270 99202
2 8 270 47768
You should use two left joins. It should be something like:
select
o.order_id,
op.product_id,
opas.options_id as size_options_id,
opac.options_id as colour_options_id
from my_order o
join order_product op on op.order_id=o.order_id
left join order_product_attribute opas
on opas.order_id=o.order_id
and opas.product_id=op.product_id
and opas.product_options=1
left join order_product_attribute opac
on opac.order_id=o.order_id
and opac.product_id=op.product_id
and opac.product_options=3
First left join is joining only with these rows which contain sizes.
Second left join is joining with rows containing colors.
You can see it in SQLFiddle

MySql get status of all records from associative table

Given the following DataBase:
CREATE TABLE album ( id int );
INSERT INTO album (id) VALUES
(1),
(2),
(3),
(4);
CREATE TABLE icon_album ( albumID int, current int );
INSERT INTO icon_album (albumID, current) VALUES
(1, 1),
(1, 1),
(2, 1),
(2, 0),
(3, 0),
(3, 0);
I would like to get the following result
albums: id status
1 1
2 0
3 0
4 0
What is the MySql query that would give me the correct result?
P.S. 1: This is my second question for this problem. This first question did not yield a working solution
Is this what you're looking for?
SELECT a.id, IF(i.current IS NULL, 0, current) AS status
FROM album a LEFT JOIN
(
SELECT albumID, MIN(current) AS current
FROM icon_album
GROUP BY albumID
) i ON a.id = i.albumID
Try Like this
"SELECT albumID AS id, if(SUM(current)>1,1,0) AS status FROM icon_album GROUP BY albumID"

How to select records only when the SUM(field) from a separate table > 0 using MAX to identify the most recent 'field'

I have been battling with this query for over a day now. My SQL is not amazing, so that might explain why! Anyway, I'd really appreciate if anyone could clarify what I'm doing wrong here.
CREATE TABLE `business` (
`business_id` int(11) NOT NULL AUTO_INCREMENT,
)
CREATE TABLE `business_unit` (
`business_unit_id` int(11) NOT NULL AUTO_INCREMENT,
`business_id` int(11) NOT NULL,
)
CREATE TABLE `offer` (
`offer_id` int(11) NOT NULL AUTO_INCREMENT,
`business_unit_id` int(11) NOT NULL,
`points_required` int(11) NOT NULL,
)
CREATE TABLE `points_balance` (
`points_balance_id` int(11) NOT NULL AUTO_INCREMENT,
`mobile_user_id` int(11) NOT NULL,
`business_unit_id` int(11) NOT NULL,
`points` int(11) NOT NULL DEFAULT '0',
`record_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
)
The data would be:
INSERT INTO `business` (`business_id`) VALUES (1);
INSERT INTO `business` (`business_id`) VALUES (2);
INSERT INTO `business_unit` (`business_unit_id`,`business_id`) VALUES (11, 1);
INSERT INTO `business_unit` (`business_unit_id`,`business_id`) VALUES (12, 1);
INSERT INTO `business_unit` (`business_unit_id`,`business_id`) VALUES (13, 2);
INSERT INTO `business_unit` (`business_unit_id`,`business_id`) VALUES (14, 2);
INSERT INTO `offer` (`offer_id`,`business_unit_id`,`points_required`) VALUES (21, 11, 50);
INSERT INTO `offer` (`offer_id`,`business_unit_id`,`points_required`) VALUES (22, 12, 50);
INSERT INTO `offer` (`offer_id`,`business_unit_id`,`points_required`) VALUES (23, 12, 60);
INSERT INTO `offer` (`offer_id`,`business_unit_id`,`points_required`) VALUES (24, 13, 100);
INSERT INTO `offer` (`offer_id`,`business_unit_id`,`points_required`) VALUES (25, 14, 30);
INSERT INTO `offer` (`offer_id`,`business_unit_id`,`points_required`) VALUES (26, 14, 150);
INSERT INTO `points_balance` (`points_balance_id`,`user_id`,`business_unit_id`,`points`,`record_created`) VALUES (31, 27, 11, 10, '2013-04-01');
INSERT INTO `points_balance` (`points_balance_id`,`user_id`,`business_unit_id`,`points`,`record_created`) VALUES (32, 27, 11, 30, '2013-04-02');
INSERT INTO `points_balance` (`points_balance_id`,`user_id`,`business_unit_id`,`points`,`record_created`) VALUES (33, 27, 12, 10, '2013-03-02');
INSERT INTO `points_balance` (`points_balance_id`,`user_id`,`business_unit_id`,`points`,`record_created`) VALUES (34, 27, 12, 20, '2013-03-04');
INSERT INTO `points_balance` (`points_balance_id`,`user_id`,`business_unit_id`,`points`,`record_created`) VALUES (34, 27, 14, 20, '2013-04-12');
INSERT INTO `points_balance` (`points_balance_id`,`user_id`,`business_unit_id`,`points`,`record_created`) VALUES (34, 27, 14, 100, '2013-04-14');
Records in the points balance table are insert only, so the user's balance for a unit is on the most recent record for that user/unit
Business units within the same business share the points balance (i.e. a user's total points is the sum of their points on the various units within that business).
I want to select offers where the user has enough points to redeem them.
SELECT up.user_id, up.points, o.*
FROM offer o
JOIN (
SELECT user_id, business_id, sum(points) AS points
FROM points_balance pb
JOIN business_unit bu on pb.business_unit_id = bu.business_unit_id
WHERE pb.points_balance_id IN (
SELECT MAX(pb2.points_balance_id)
FROM points_balance pb2
WHERE pb2.user_id = 27
GROUP BY pb2.business_unit_id)
GROUP BY user_id, business_id
) up ON up.points >= o.points_required
The query above is returning one instance of the same offer multiple times (times the number of business the user has points at) :(
The result set I'm looking for is:
user_id | points | offer_id
27 | 50 | 21
27 | 50 | 22
27 | 100 | 24
27 | 100 | 25
Thanks all.
G
Here is a query that does what I think you want:
select up.user_id, up.business_id, up.allpoints, o.*
from (select user_id, business_id, sum(points_balance) as allpoints
from points_balance pb join
business_Unit bu
on pb.business_unit_id = bu.business_unit_id
group by user_id, business_id
) up join
offers o
on o.point_required <= up.allpoints;
The logic behind this query is much simpler than the approach you were taking. The first subquery calculates the total number of points available for a user across all business units within a business. It then finds the matching points.
You can add where clauses either in the subquery or in the overall query to limit to particular businesses or users.
Also, this is based on the field names in the text of the question, not the ones in the query. They are different.
I found out it was returning multiple instances of the same offer when I had points to redeem the offer in multiple business. So the problem is that I was not linking the offer to the specific business! so I added to the bottom of the query
JOIN business_unit bu ON bu.business_unit_id = o.business_unit_id
AND up.business_id = bu.business_id
Sorted :)