Querying Many to Many When 3 Tables Connected to A junction - many-to-many

DB MODEL
I have Model Which is Connected in above Order Now I want to Select Style Names From Style Table.
Case 1 : I want the Style Names which are both intersecting Category and Gender
Case 2 : I want the Style Names which are intersecting Gender only regardless of category.
I am newbie to SQL is there any efficient way to Get the desired result using SQL JOINS . Any Help in such case will be appreciated or is there any modelling solutions to deal with such type of situations.

Here is how you would join your tables:
SELECT *
FROM `style`
INNER JOIN `StyleCategoryGender` ON `StyleCategoryGender`.`SID` = `style`.`Code`
INNER JOIN `StyleCategoryGender` ON `Category`.`Code` = `StyleCategoryGender`.`GID`
INNER JOIN `StyleCategoryGender` ON `Gender`.`Code` = `StyleCategoryGender`.`CID`
then you can add WHERE clauses as needed
SELECT *
FROM `style`
INNER JOIN `StyleCategoryGender` ON `StyleCategoryGender`.`SID` = `style`.`CODE`
INNER JOIN `StyleCategoryGender` ON `Category`.`Code` = `StyleCategoryGender`.`GID`
INNER JOIN `StyleCategoryGender` ON `Gender`.`Code` = `StyleCategoryGender`.`CID`
WHERE `Gender`.`Name` = 'Female'

Related

Select all rows with multiple possible values

I am trying to get all fields from the product table (*) that have the following set of sub_property:
subprop_name=X
subprop_value=Y
I have the following tables :
https://imgur.com/a/y4LGqMI (couldn't upload the picture because the format was not accepted)
So, for an example, if I have two products which has in their sub_property table a entry like this:
subprop_name=X
subprop_value=Y
I would like to return it. As described by the schema, a product can have multiple sub_property entries!
So far, this is what I have:
SELECT prod_id,prod_name from product WHERE product.prod_id IN
(
SELECT property.product_prod_id FROM property WHERE property.prop_id IN
(
SELECT property_prop_id from sub_property WHERE
(
sub_property.subprop_name="Type de scanner" AND sub_property.subprop_value="par transparence"
)
OR
(
sub_property.subprop_name="Pages/minute maximum" AND subprop_value="8.5 pages"
)
)
)
But obviously, it doesn't work because of the 'OR'.
It returns me all items that have one of the set of sub_property instead of all the products that have all the sets of sub_property.
DATABASE HERE
Using JOIN's and an IN for the tupples could be a simple solution for this.
SELECT p.prod_id, p.prod_name
FROM product p
JOIN property AS prop
ON prop.product_prod_id = p.prod_id
JOIN sub_property AS subprop
ON subprop.property_prop_id = prop.prop_id
WHERE (subprop.subprop_name, subprop.subprop_value) IN (
('Type de scanner', 'par transparence'),
('Pages/minute maximum', '8.5 pages')
)
GROUP BY p.prod_id, p.prod_name
So... I am not sure if it's the correct way to validate two answers, but I got 2 working answers.
This is the first one from #Steff Mächtel using LEFT JOIN (https://stackoverflow.com/a/53915792/5454875)
And the second one is from #Shidersz (see comments below the original question), using INNER JOIN)
"I used and approach using INNER JOIN, is something like this what you need? db-fiddle.com/f/t6RrnhDPQuEamjf2bTxFeX/5"
EDIT
#Shidersz solution doesn't work because it selects all products who as at least one of the condition, wich I don't want. I want the product to have all the conditions.
UPDATE 2:
I would suggest to use LEFT JOIN for each property and each sub_property and then check the value inside WHERE condition:
SELECT product.prod_id, product.prod_name
FROM product
LEFT JOIN property AS property_a ON property_a.product_prod_id = product.prod_id AND
property_a.prop_name = "PROPERTY_GROUP_3"
LEFT JOIN sub_property AS sub_property_a ON sub_property_a.property_prop_id = property_a.prop_id AND
sub_property_a.subprop_name="property_4"
LEFT JOIN property AS property_b ON property_b.product_prod_id = product.prod_id AND
property_b.prop_name = "PROPERTY_GROUP_4"
LEFT JOIN sub_property AS sub_property_b ON sub_property_b.property_prop_id = property_b.prop_id AND
sub_property_b.subprop_name="property_3"
WHERE sub_property_a.subprop_value="value_of_property_4" AND
sub_property_b.subprop_value="value_of_property_3"
GROUP BY product.prod_id
Example: https://www.db-fiddle.com/f/wk344Gt6hm98xEhM4jei92/6
Example with 2 new "KEYS" (Index) for better performance:
ALTER TABLE `property`
... ADD KEY `prop_name` (`prop_name`);
ALTER TABLE `sub_property`
... ADD KEY `subprop_name` (`subprop_name`);
https://www.db-fiddle.com/f/wk344Gt6hm98xEhM4jei92/7
Example with INNER JOIN instead of LEFT JOIN
I see no difference with EXPLAIN on test data, maybe Mysql optimizer handles this internal equal
SELECT product.prod_id, product.prod_name
FROM product
INNER JOIN property AS property_a ON property_a.product_prod_id = product.prod_id AND
property_a.prop_name = "PROPERTY_GROUP_3"
INNER JOIN sub_property AS sub_property_a ON sub_property_a.property_prop_id = property_a.prop_id AND
sub_property_a.subprop_name="property_4" AND
sub_property_a.subprop_value="value_of_property_4"
INNER JOIN property AS property_b ON property_b.product_prod_id = product.prod_id AND
property_b.prop_name = "PROPERTY_GROUP_4"
INNER JOIN sub_property AS sub_property_b ON sub_property_b.property_prop_id = property_b.prop_id AND
sub_property_b.subprop_name="property_3" AND
sub_property_b.subprop_value="value_of_property_3"
GROUP BY product.prod_id
https://www.db-fiddle.com/f/wk344Gt6hm98xEhM4jei92/8

Select rows based on an array of values and join data

I have a MySQL database of contacts with three tables.
person
personContact
personDetails
Each contact shares a primary key called 'ID'
The personContact table contains a value called 'personZip' which happens to be their mailing address zip code.
I'd like to write a SQL query that will give me all the contact data for each person in a specific array of zip codes.
I've written a simple statement to perform an inner join on 2 of the tables:
SELECT * FROM `personContact`
INNER JOIN person
ON personContact.ID=person.ID
I've written a statement to select only the zip codes I need:
SELECT * FROM 'personContact'
WHERE personContact.personZip=12564
OR personContact.personZip=12563
OR personContact.personZip=12522
OR personContact.personZip=12590
OR personContact.personZip=12594
OR personContact.personZip=12533
OR personContact.personZip=12570
OR personContact.personZip=12589
OR personContact.personZip=10509
I'm not sure how to perform two joins, to merge all columns from all three tables.
I'm not sure how to write the query to accommodate both the selection of zip codes and the JOINS.
MySQL errors are not helping me move in the right direction.
You were almost there. Use in which is equivalent to or.
SELECT pc.* --select columns from the other tables as needed.
FROM
`personContact` pc
INNER JOIN person p ON pc.ID = p.ID
INNER JOIN personDetails pd on pd.ID = p.ID
where pc.personzip in (12563, 12522, 10509) -- add more zips as needed
Join all three tables and return all columns while filtering by zip code:
SELECT person.*, personContact.*, personDetails.*
FROM person
INNER JOIN personContact ON personContact.ID = person.ID
INNER JOIN personDetails ON personDetails.ID = person.ID
WHERE personContact.personZip = 12564
OR personContact.personZip = 12563
OR personContact.personZip = 12522
OR personContact.personZip = 12590
OR personContact.personZip = 12594
OR personContact.personZip = 12533
OR personContact.personZip = 12570
OR personContact.personZip = 12589
OR personContact.personZip = 10509
EDIT: Multiple OR statements can be replaced using IN as others have suggested
WHERE personContact.personZip IN (12564, 12563, 12522, 12590 ...)

MySQL join & search

I have a problem with joining some tables, heres my structure:
tbl_imdb:
fldID fldTitle fldImdbID
1 Moviename 0000001
tbl_genres:
fldID fldGenre
1 Action
2 Drama
tbl_genres_rel:
fldID fldMovieID fldGenreID
1 1 1
2 1 2
What I’m trying to do is a query that will find all movies that is both an action movie and drama, is this possible to do without a subquery, if so, how?
What I'm trying right now is:
SELECT tbl_imdb.*
FROM tbl_imdb
LEFT JOIN tbl_imdb_genres_rel ON ( tbl_imdb.fldID = tbl_imdb_genres_rel.fldMovieID )
LEFT JOIN tbl_imdb_genres ON ( tbl_imdb_genres_rel.fldGenreID = tbl_imdb_genres.fldID )
WHERE tbl_imdb_genres.fldGenre = 'Drama'
AND tbl_imdb_genres.fldGenre = 'Action';
But this dosnt work, however it does work if I only keep one of the two WHERE's, but thats not what I want.
Two ways to do it:
1
SELECT tbl_imdb.*
FROM tbl_imdb
INNER JOIN tbl_genres_rel rel_action
ON tbl_imdb.fldID = rel_action.fldMovieID
INNER JOIN tbl_genres genre_action
ON rel_action.fldGenreId = genre_action.fldID
AND 'Action' = genre_action.fldGenre
INNER JOIN tbl_genres_rel rel_drama
ON tbl_imdb.fldID = rel_drama.fldMovieID
INNER JOIN tbl_genres genre_drama
ON rel_drama.fldGenreId = genre_drama.fldID
AND 'Drama' = genre_drama.fldGenre
This method is on the same path as your original solution. 2 differences:
The join should be inner, not left because you're trying to get movies that certainly have the corresponding genre entry
Since you want to find 2 different generes, you'll have to do the join with tbl_genres_rel and tbl_genres twice, once for each particular genre you're interested in.
2
SELECT tbl_imdb.*
FROM tbl_imdb
INNER JOIN tbl_genres_rel
ON tbl_imdb.fldID = tbl_genres_rel.fldMovieID
INNER JOIN tbl_genres
ON tbl_genres_rel.fldGenreId = tbl_genres.fldID
AND tbl_genres.fldGenre IN ('Action', 'Drama')
GROUP BY tbl_imdb.fldID
HAVING COUNT(*) = 2
Again, the basic join plan is the same. Difference here is that we join to the tbl_genres_rel and tbl_genres path just once. This on itself fetches all genres for one film, and then filters for the one's you're interested in. The ones that qualify will now have 2 rows for each distinct value of tbl_imdb.fldId. The GROUP BY aggregates on that, flattening that into one row. By asserting in the HAVING clause that we have exactly 2 rows, we ensure that we keep only those rows that have both the genres.
(Note that this assumes that there is a unique constraint on tbl_genres_rel over {fldMovieID, fldGenreID}. If such a constraint is not present, you should consider adding it.)
LEFT JOIN is not applicable in your case because records should exist on both tables. And you need to count the instances of the movie
SELECT *
FROM tbl_imdb a
INNER JOIN tbl_genres_rel b
on a.fldID = fldMovieID
INNER JOIN tbl_genres c
on c.fldGenreID = b.fldID
WHERE c.fldGenre IN ('Drama', 'Action')
GROUP BY a.Moviename
HAVING COUNT(*) > 1

MySQL - Using column value for joining in the same query

I have three tables that looks something like this:
Table joins
|ID|JOIN_NAME|
1 persons
2 companies
Table information
|ID|JOIN_ID|
1 1
2 2
Table information_extra_persons
|ID|INFORMATION_ID|NAME|
1 1 John
Table information_extra_companies
|ID|INFORMATION_ID|NAME|
1 2 IBM
How can i join together these tables in one SQL? I've tried something like:
SELECT * FROM `information`
INNER JOIN `information_extra_(SELECT `name` FROM `joins` WHERE `id` = `join_id`)`
ON `information_extra_(SELECT `name` FROM `joins` WHERE `id` = `join_id`)`.`information_id` = `information`.`id`
but I can't get it to work. Of course this isn't my actual table setup, but it's the same principle. Does anyone know how to get all the info in just one SQL?
That's actually four tables, not three. This isn't just a nitpick - it looks as though the substance of your question is "how can I use the name of the table as part of the join criteria?" (ie. how can the information_extra_ tables be treated as a single table?)
To which the answer is: you can't. (Outside of dynamic SQL.)
In this specific case, the following should return what I think you are looking for:
select j.join_name joined_entity,
case when j.join_name = 'persons' then p.name
else c.name
end joined_entity_name
from information i
inner join joins j on i.join_id = j.id
left join information_extra_persons p on i.id = p.information_id
left join information_extra_companies c on i.id = c.information_id
Alternatively, a less efficient (but more general) approach might be:
select j.join_name joined_entity,
v.name joined_entity_name
from information i
inner join joins j on i.join_id = j.id
inner join (select 'persons' entity, information_id, name from information_extra_persons
union all
select 'companies' entity, information_id, name from information_extra_companies) v
on i.id = v.information_id and j.join_name = v.entity

SQL Select multiple column values

I'm having difficulty with some SQL - and finding it hard to describe so please bear with me. I'm trying to select products that have an x number of correct features. To simplify things, the problem I'm having is with a few tables. The relevant information about my tables, is:
products(**product_id**)
features(**feature_id, product_id**, value_id)
featurenames(**feature_id**, name)
featurevalues(**value_id**, value)
I am trying to select all products that, for example, are for sex:male age:children, with age and sex being names in the featurenames table and male and children being values in the featurevalues table. This is part of another bigger query that gets all the products by category, which I haven't included as it will just complicate things. Thank you for your help in advance.
It's the table so nice, you join to it twice.
Select
P.Product_ID
From
Products P
Inner Join Features F1 On P.Product_ID = F1.Product_ID
Inner Join FeatureNames FN1 On F1.Feature_ID = FN1.Feature_ID And FN1.Name = 'sex'
Inner Join FeatureValues FV1 On F1.Value_ID = FV1.Value_ID And FV1.Value = 'male'
Inner Join Features F2 On P.Product_ID = F2.Product_ID
Inner Join FeatureNames FN2 On F2.Feature_ID = FN2.Feature_ID And FN1.Name = 'age'
Inner Join FeatureValues FV2 On F2.Value_ID = FV2.Value_ID And FV1.Value = 'children'