MySQL: JOIN and WHERE with multiple matchesWhat is the difference between “INNER JOIN” and “OUTER JOIN”?Should I use the datetime or timestamp data type in MySQL?Python join: why is it string.join(list) instead of list.join(string)?Difference between JOIN and INNER JOININNER JOIN ON vs WHERE clauseWhat's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?How do I import an SQL file using the command line in MySQL?mysql relation slowJOIN Query In MYSQL and PHPMYSQL Error Installing BuildEngine
Help me, I hate squares!
Why are we moving in circles with a tandem kayak?
How did Biff return to 2015 from 1955 without a lightning strike?
Applying for mortgage when living together but only one will be on the mortgage
How do discovery writers hibernate?
Why does macOS create file mounts for each app?
What force enables us to walk? Friction or normal reaction?
Were there any unmanned expeditions to the moon that returned to Earth prior to Apollo?
How to structure presentation to avoid getting questions that will be answered later in the presentation?
Can you remove a blindfold using the Telekinesis spell?
How do I respond appropriately to an overseas company that obtained a visa for me without hiring me?
Why is the Searing Smite spell not listed in the Roll20 spell list?
Adding a (stair/baby) gate without facing walls
Scam? Checks via Email
Reducing the time for rolling hash
Just how much information should you share with a former client?
My employer is refusing to give me the pay that was advertised after an internal job move
Why do we need a voltage divider when we get the same voltage at the output as the input?
Why are prop blades not shaped like household fan blades?
Applications of pure mathematics in operations research
What is my clock telling me to do?
how can I calculate confidence interval with small sample in R?
How to remove rebar passing through an inaccessible pipe
Why was the Lobbying Transparency and Accountability Act of 2006 deemed too weak?
MySQL: JOIN and WHERE with multiple matches
What is the difference between “INNER JOIN” and “OUTER JOIN”?Should I use the datetime or timestamp data type in MySQL?Python join: why is it string.join(list) instead of list.join(string)?Difference between JOIN and INNER JOININNER JOIN ON vs WHERE clauseWhat's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?How do I import an SQL file using the command line in MySQL?mysql relation slowJOIN Query In MYSQL and PHPMYSQL Error Installing BuildEngine
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I would like to select products from products
table with the attributes with id 2 and 5 using the following query:
SELECT `products`.`title`, `products`.`price`
FROM `products`
LEFT JOIN `products_attributes_mapping`
ON `products`.`id` = `products_attributes_mapping`.`product_id`
WHERE
`products_attributes_mapping`.`attribute_value_id` IN (2)
AND `products_attributes_mapping`.`attribute_value_id` IN (5)
GROUP BY `products`.`id`
I expect the product 'Example product 1, blue, size 1'
to be returned. But I don't get any result, even though the product with id 1 has attribute_value_id
2 and 5 assigned in the products_attributes_mapping
table.
I use IN
because I would like to be able to provide multiple attributes, I simplified it only for the example.
SQL fiddle: http://sqlfiddle.com/#!9/2fd94f2/1/0
Schema
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET utf8 NOT NULL,
`price` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes_mapping` (
`product_id` int(11) NOT NULL,
`attribute_value_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes_values` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`attribute_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
Data
INSERT INTO `products` VALUES
(1,'Example product 1, blue, size 1',10),
(2,'Example product 2, yellow, size 1',10),
(3,'Example product 3, black, size 2',15),
(4,'Example product 4, red, size 2',15);
INSERT INTO `products_attributes` VALUES
(1,'Color'),
(2,'Size');
INSERT INTO `products_attributes_mapping` VALUES
(1,2),
(1,5),
(2,4),
(2,5),
(3,3),
(3,6),
(4,1),
(4,6);
INSERT INTO `products_attributes_values` VALUES
(1,1,'red'),
(2,1,'blue'),
(3,1,'black'),
(4,1,'yellow'),
(5,2,'1'),
(6,2,'2'),
(7,2,'3'),
(8,2,'4');
mysql sql join
|
show 1 more comment
I would like to select products from products
table with the attributes with id 2 and 5 using the following query:
SELECT `products`.`title`, `products`.`price`
FROM `products`
LEFT JOIN `products_attributes_mapping`
ON `products`.`id` = `products_attributes_mapping`.`product_id`
WHERE
`products_attributes_mapping`.`attribute_value_id` IN (2)
AND `products_attributes_mapping`.`attribute_value_id` IN (5)
GROUP BY `products`.`id`
I expect the product 'Example product 1, blue, size 1'
to be returned. But I don't get any result, even though the product with id 1 has attribute_value_id
2 and 5 assigned in the products_attributes_mapping
table.
I use IN
because I would like to be able to provide multiple attributes, I simplified it only for the example.
SQL fiddle: http://sqlfiddle.com/#!9/2fd94f2/1/0
Schema
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET utf8 NOT NULL,
`price` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes_mapping` (
`product_id` int(11) NOT NULL,
`attribute_value_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes_values` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`attribute_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
Data
INSERT INTO `products` VALUES
(1,'Example product 1, blue, size 1',10),
(2,'Example product 2, yellow, size 1',10),
(3,'Example product 3, black, size 2',15),
(4,'Example product 4, red, size 2',15);
INSERT INTO `products_attributes` VALUES
(1,'Color'),
(2,'Size');
INSERT INTO `products_attributes_mapping` VALUES
(1,2),
(1,5),
(2,4),
(2,5),
(3,3),
(3,6),
(4,1),
(4,6);
INSERT INTO `products_attributes_values` VALUES
(1,1,'red'),
(2,1,'blue'),
(3,1,'black'),
(4,1,'yellow'),
(5,2,'1'),
(6,2,'2'),
(7,2,'3'),
(8,2,'4');
mysql sql join
2
One .. You don't need theAND
statment:AND products_attributes_mapping.attribute_value_id IN (5)
because you're usingIN
.. On the originalWHERE
just use:attribute_value_id IN (2,5)
– Zak
Mar 26 at 22:31
YourWHERE
has you trying to select a record that has anattribute_value_id
of both 2 & 5.
– ItsPete
Mar 26 at 22:35
How wouldproducts_attributes_mapping.attribute_value_id IN (2) AND products_attributes_mapping.attribute_value_id IN (5)
ever return any result?attribute_value_id
can't be both 2 and 5 at the same time.
– Eric
Mar 26 at 22:49
@ItsPete @Eric That's what I want. I would like to get the product which have inproducts_attributes_mapping
assignedattribute_value_id
2 and 5 at the same time. And there are the corresponding entries:INSERT INTO products_attributes_mapping VALUES (1,2) (1,5);
– Hativ
Mar 27 at 0:00
1
@Hativ The problem with your current query is that it for this query to produce any results, a single record inproducts_attributes_mapping
must be both 2 & 5. Since it is only ever one value at a time, no results are returned. GMB's solution below will allow you to specify that products require multiple attributes.
– ItsPete
Mar 27 at 1:06
|
show 1 more comment
I would like to select products from products
table with the attributes with id 2 and 5 using the following query:
SELECT `products`.`title`, `products`.`price`
FROM `products`
LEFT JOIN `products_attributes_mapping`
ON `products`.`id` = `products_attributes_mapping`.`product_id`
WHERE
`products_attributes_mapping`.`attribute_value_id` IN (2)
AND `products_attributes_mapping`.`attribute_value_id` IN (5)
GROUP BY `products`.`id`
I expect the product 'Example product 1, blue, size 1'
to be returned. But I don't get any result, even though the product with id 1 has attribute_value_id
2 and 5 assigned in the products_attributes_mapping
table.
I use IN
because I would like to be able to provide multiple attributes, I simplified it only for the example.
SQL fiddle: http://sqlfiddle.com/#!9/2fd94f2/1/0
Schema
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET utf8 NOT NULL,
`price` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes_mapping` (
`product_id` int(11) NOT NULL,
`attribute_value_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes_values` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`attribute_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
Data
INSERT INTO `products` VALUES
(1,'Example product 1, blue, size 1',10),
(2,'Example product 2, yellow, size 1',10),
(3,'Example product 3, black, size 2',15),
(4,'Example product 4, red, size 2',15);
INSERT INTO `products_attributes` VALUES
(1,'Color'),
(2,'Size');
INSERT INTO `products_attributes_mapping` VALUES
(1,2),
(1,5),
(2,4),
(2,5),
(3,3),
(3,6),
(4,1),
(4,6);
INSERT INTO `products_attributes_values` VALUES
(1,1,'red'),
(2,1,'blue'),
(3,1,'black'),
(4,1,'yellow'),
(5,2,'1'),
(6,2,'2'),
(7,2,'3'),
(8,2,'4');
mysql sql join
I would like to select products from products
table with the attributes with id 2 and 5 using the following query:
SELECT `products`.`title`, `products`.`price`
FROM `products`
LEFT JOIN `products_attributes_mapping`
ON `products`.`id` = `products_attributes_mapping`.`product_id`
WHERE
`products_attributes_mapping`.`attribute_value_id` IN (2)
AND `products_attributes_mapping`.`attribute_value_id` IN (5)
GROUP BY `products`.`id`
I expect the product 'Example product 1, blue, size 1'
to be returned. But I don't get any result, even though the product with id 1 has attribute_value_id
2 and 5 assigned in the products_attributes_mapping
table.
I use IN
because I would like to be able to provide multiple attributes, I simplified it only for the example.
SQL fiddle: http://sqlfiddle.com/#!9/2fd94f2/1/0
Schema
CREATE TABLE `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) CHARACTER SET utf8 NOT NULL,
`price` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes_mapping` (
`product_id` int(11) NOT NULL,
`attribute_value_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `products_attributes_values` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`attribute_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
Data
INSERT INTO `products` VALUES
(1,'Example product 1, blue, size 1',10),
(2,'Example product 2, yellow, size 1',10),
(3,'Example product 3, black, size 2',15),
(4,'Example product 4, red, size 2',15);
INSERT INTO `products_attributes` VALUES
(1,'Color'),
(2,'Size');
INSERT INTO `products_attributes_mapping` VALUES
(1,2),
(1,5),
(2,4),
(2,5),
(3,3),
(3,6),
(4,1),
(4,6);
INSERT INTO `products_attributes_values` VALUES
(1,1,'red'),
(2,1,'blue'),
(3,1,'black'),
(4,1,'yellow'),
(5,2,'1'),
(6,2,'2'),
(7,2,'3'),
(8,2,'4');
mysql sql join
mysql sql join
edited Mar 26 at 22:42
GMB
22.3k6 gold badges11 silver badges28 bronze badges
22.3k6 gold badges11 silver badges28 bronze badges
asked Mar 26 at 22:26
HativHativ
9349 silver badges21 bronze badges
9349 silver badges21 bronze badges
2
One .. You don't need theAND
statment:AND products_attributes_mapping.attribute_value_id IN (5)
because you're usingIN
.. On the originalWHERE
just use:attribute_value_id IN (2,5)
– Zak
Mar 26 at 22:31
YourWHERE
has you trying to select a record that has anattribute_value_id
of both 2 & 5.
– ItsPete
Mar 26 at 22:35
How wouldproducts_attributes_mapping.attribute_value_id IN (2) AND products_attributes_mapping.attribute_value_id IN (5)
ever return any result?attribute_value_id
can't be both 2 and 5 at the same time.
– Eric
Mar 26 at 22:49
@ItsPete @Eric That's what I want. I would like to get the product which have inproducts_attributes_mapping
assignedattribute_value_id
2 and 5 at the same time. And there are the corresponding entries:INSERT INTO products_attributes_mapping VALUES (1,2) (1,5);
– Hativ
Mar 27 at 0:00
1
@Hativ The problem with your current query is that it for this query to produce any results, a single record inproducts_attributes_mapping
must be both 2 & 5. Since it is only ever one value at a time, no results are returned. GMB's solution below will allow you to specify that products require multiple attributes.
– ItsPete
Mar 27 at 1:06
|
show 1 more comment
2
One .. You don't need theAND
statment:AND products_attributes_mapping.attribute_value_id IN (5)
because you're usingIN
.. On the originalWHERE
just use:attribute_value_id IN (2,5)
– Zak
Mar 26 at 22:31
YourWHERE
has you trying to select a record that has anattribute_value_id
of both 2 & 5.
– ItsPete
Mar 26 at 22:35
How wouldproducts_attributes_mapping.attribute_value_id IN (2) AND products_attributes_mapping.attribute_value_id IN (5)
ever return any result?attribute_value_id
can't be both 2 and 5 at the same time.
– Eric
Mar 26 at 22:49
@ItsPete @Eric That's what I want. I would like to get the product which have inproducts_attributes_mapping
assignedattribute_value_id
2 and 5 at the same time. And there are the corresponding entries:INSERT INTO products_attributes_mapping VALUES (1,2) (1,5);
– Hativ
Mar 27 at 0:00
1
@Hativ The problem with your current query is that it for this query to produce any results, a single record inproducts_attributes_mapping
must be both 2 & 5. Since it is only ever one value at a time, no results are returned. GMB's solution below will allow you to specify that products require multiple attributes.
– ItsPete
Mar 27 at 1:06
2
2
One .. You don't need the
AND
statment: AND products_attributes_mapping.attribute_value_id IN (5)
because you're using IN
.. On the original WHERE
just use: attribute_value_id IN (2,5)
– Zak
Mar 26 at 22:31
One .. You don't need the
AND
statment: AND products_attributes_mapping.attribute_value_id IN (5)
because you're using IN
.. On the original WHERE
just use: attribute_value_id IN (2,5)
– Zak
Mar 26 at 22:31
Your
WHERE
has you trying to select a record that has an attribute_value_id
of both 2 & 5.– ItsPete
Mar 26 at 22:35
Your
WHERE
has you trying to select a record that has an attribute_value_id
of both 2 & 5.– ItsPete
Mar 26 at 22:35
How would
products_attributes_mapping.attribute_value_id IN (2) AND products_attributes_mapping.attribute_value_id IN (5)
ever return any result? attribute_value_id
can't be both 2 and 5 at the same time.– Eric
Mar 26 at 22:49
How would
products_attributes_mapping.attribute_value_id IN (2) AND products_attributes_mapping.attribute_value_id IN (5)
ever return any result? attribute_value_id
can't be both 2 and 5 at the same time.– Eric
Mar 26 at 22:49
@ItsPete @Eric That's what I want. I would like to get the product which have in
products_attributes_mapping
assigned attribute_value_id
2 and 5 at the same time. And there are the corresponding entries: INSERT INTO products_attributes_mapping VALUES (1,2) (1,5);
– Hativ
Mar 27 at 0:00
@ItsPete @Eric That's what I want. I would like to get the product which have in
products_attributes_mapping
assigned attribute_value_id
2 and 5 at the same time. And there are the corresponding entries: INSERT INTO products_attributes_mapping VALUES (1,2) (1,5);
– Hativ
Mar 27 at 0:00
1
1
@Hativ The problem with your current query is that it for this query to produce any results, a single record in
products_attributes_mapping
must be both 2 & 5. Since it is only ever one value at a time, no results are returned. GMB's solution below will allow you to specify that products require multiple attributes.– ItsPete
Mar 27 at 1:06
@Hativ The problem with your current query is that it for this query to produce any results, a single record in
products_attributes_mapping
must be both 2 & 5. Since it is only ever one value at a time, no results are returned. GMB's solution below will allow you to specify that products require multiple attributes.– ItsPete
Mar 27 at 1:06
|
show 1 more comment
1 Answer
1
active
oldest
votes
Using aggregation could indeed be a solution. You can use a HAVING
clause to ensure that a products has certain attribute values:
SELECT p.title, p.price
FROM products p
INNER JOIN products_attributes_mapping pm ON p.id = pm.product_id
GROUP BY p.id, p.title, p.price
HAVING
MAX(pm.attribute_value_id = 2) = 1
AND MAX(pm.attribute_value_id = 5) = 1
In your DB fiddle, this query returns:
title | price
---------------------------------|-------
Example product 1, blue, size 1 | 10
You can easily extend the expression by adding more AND MAX(...) = 1
conditions.
Another option would be to use a series of WHERE EXISTS
conditions with correlated subqueries to search the attributes tables. This is just as good, but will expand as a longer query if you need to add many conditions.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55367045%2fmysql-join-and-where-with-multiple-matches%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Using aggregation could indeed be a solution. You can use a HAVING
clause to ensure that a products has certain attribute values:
SELECT p.title, p.price
FROM products p
INNER JOIN products_attributes_mapping pm ON p.id = pm.product_id
GROUP BY p.id, p.title, p.price
HAVING
MAX(pm.attribute_value_id = 2) = 1
AND MAX(pm.attribute_value_id = 5) = 1
In your DB fiddle, this query returns:
title | price
---------------------------------|-------
Example product 1, blue, size 1 | 10
You can easily extend the expression by adding more AND MAX(...) = 1
conditions.
Another option would be to use a series of WHERE EXISTS
conditions with correlated subqueries to search the attributes tables. This is just as good, but will expand as a longer query if you need to add many conditions.
add a comment |
Using aggregation could indeed be a solution. You can use a HAVING
clause to ensure that a products has certain attribute values:
SELECT p.title, p.price
FROM products p
INNER JOIN products_attributes_mapping pm ON p.id = pm.product_id
GROUP BY p.id, p.title, p.price
HAVING
MAX(pm.attribute_value_id = 2) = 1
AND MAX(pm.attribute_value_id = 5) = 1
In your DB fiddle, this query returns:
title | price
---------------------------------|-------
Example product 1, blue, size 1 | 10
You can easily extend the expression by adding more AND MAX(...) = 1
conditions.
Another option would be to use a series of WHERE EXISTS
conditions with correlated subqueries to search the attributes tables. This is just as good, but will expand as a longer query if you need to add many conditions.
add a comment |
Using aggregation could indeed be a solution. You can use a HAVING
clause to ensure that a products has certain attribute values:
SELECT p.title, p.price
FROM products p
INNER JOIN products_attributes_mapping pm ON p.id = pm.product_id
GROUP BY p.id, p.title, p.price
HAVING
MAX(pm.attribute_value_id = 2) = 1
AND MAX(pm.attribute_value_id = 5) = 1
In your DB fiddle, this query returns:
title | price
---------------------------------|-------
Example product 1, blue, size 1 | 10
You can easily extend the expression by adding more AND MAX(...) = 1
conditions.
Another option would be to use a series of WHERE EXISTS
conditions with correlated subqueries to search the attributes tables. This is just as good, but will expand as a longer query if you need to add many conditions.
Using aggregation could indeed be a solution. You can use a HAVING
clause to ensure that a products has certain attribute values:
SELECT p.title, p.price
FROM products p
INNER JOIN products_attributes_mapping pm ON p.id = pm.product_id
GROUP BY p.id, p.title, p.price
HAVING
MAX(pm.attribute_value_id = 2) = 1
AND MAX(pm.attribute_value_id = 5) = 1
In your DB fiddle, this query returns:
title | price
---------------------------------|-------
Example product 1, blue, size 1 | 10
You can easily extend the expression by adding more AND MAX(...) = 1
conditions.
Another option would be to use a series of WHERE EXISTS
conditions with correlated subqueries to search the attributes tables. This is just as good, but will expand as a longer query if you need to add many conditions.
answered Mar 26 at 22:35
GMBGMB
22.3k6 gold badges11 silver badges28 bronze badges
22.3k6 gold badges11 silver badges28 bronze badges
add a comment |
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55367045%2fmysql-join-and-where-with-multiple-matches%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
One .. You don't need the
AND
statment:AND products_attributes_mapping.attribute_value_id IN (5)
because you're usingIN
.. On the originalWHERE
just use:attribute_value_id IN (2,5)
– Zak
Mar 26 at 22:31
Your
WHERE
has you trying to select a record that has anattribute_value_id
of both 2 & 5.– ItsPete
Mar 26 at 22:35
How would
products_attributes_mapping.attribute_value_id IN (2) AND products_attributes_mapping.attribute_value_id IN (5)
ever return any result?attribute_value_id
can't be both 2 and 5 at the same time.– Eric
Mar 26 at 22:49
@ItsPete @Eric That's what I want. I would like to get the product which have in
products_attributes_mapping
assignedattribute_value_id
2 and 5 at the same time. And there are the corresponding entries:INSERT INTO products_attributes_mapping VALUES (1,2) (1,5);
– Hativ
Mar 27 at 0:00
1
@Hativ The problem with your current query is that it for this query to produce any results, a single record in
products_attributes_mapping
must be both 2 & 5. Since it is only ever one value at a time, no results are returned. GMB's solution below will allow you to specify that products require multiple attributes.– ItsPete
Mar 27 at 1:06