How to inner join a lookup table for a mysql query? - mysql

I need help with a mysql query using the following two tables:
profiles (TABLE 1)
id user_id gender age height bodytype
1 1 1 57 1 2
2 2 2 32 2 1
profile_lookup (TABLE 2)
id option_group option_value option_name
1 gender 1 Female
2 gender 2 Male
3 gender 3 Prefer not to say
4 height 1 5 ft - 6 in
5 height 2 5ft - 9 in
6 bodytype 1 Petite/slim
7 bodytype 2 Average
There are whole lot of other options and option values that i am omitting for the sake of brevity
I am interested to do inner join queries using the syntax as shown below:
SELECT *
FROM profiles
WHERE bodytype = 2
JOIN profile_lookup
ON profiles.gender = profile_lookup..... (not sure)
Request help with using the correct syntax using the above two tables. Thanks

I think you want:
SELECT p.*, plg.option_name as gender
FROM profiles p INNER JOIN
profile_lookup plg
ON plg.option_group = 'gender' and
plg.option_value = p.gender
WHERE p.bodytype = 2 ;
You can extend this to other columns. You might want a LEFT JOIN in case some values don't match (i.e. are NULL):
SELECT p.*, plg.option_name as gender, plh.option_name as height
FROM profiles p LEFT JOIN
profile_lookup plg
ON plg.option_group = 'gender' AND
plg.option_value = p.gender LEFT JOIN
profile_lookup plh
ON plh.option_group = 'height' AND
plh.option_value = p.height
WHERE p.bodytype = 2

The where clause should be after the JOIN clause
SELECT * FROM profiles
INNER JOIN profile_lookup ON profiles.gender = profile_lookup.option_value
and profile_lookup.option_group = 'gender'
WHERE profiles.bodytype = 2
and for the join you need the proper profile_lookup.option_value

Related

How can I do SQL query based on two conditions on two columns?

see the EARD scenario
Major_applied_for table
id
preference
application_number (fk)
major_code (fk)
1
1
2
1
2
1
1
1
3
3
3
1
4
2
1
2
5
2
2
2
Some Clarifications:
• The code attribute of Major table holds (1)CS for computer science, (2)BMS for business management and so on.
• preference attribute of Major_Applied_For is 1, 2 or 3 (1 for being the first
choice, 2 being the second choice and 3 being the third choice)
.
.
.
This is a table that many to many relationship resolved in, I wanna get all the application numbers that have CS as the first choice and BMS as the second choice.
I tried this sql statement but it's logically incorrect.
SELECT m.id, CONCAT(m.fname, " ", m.lname) AS Fullname, app.number AS application_no
FROM applicant m, application app, major_applied_for mjaf
WHERE ((mjaf.major_code = 1 AND mjaf.preference = 1) AND (mjaf.major_code = 2 AND mjaf.preference = 2) AND (mjaf.application_number = app.number AND app.applicant_id = m.id));
How can I resolve this issue?
Find the applicants with CS as their first pref, find the applicants with BMS their second pref. Inner join these two sets and check their names.
with first_cs as (
select c.applicant_id
from major_applied_for a inner join major b on a.major_code = b.code and a.preference = 1 and b.name = 'CS'
inner join application c on a.application_number = c.number ), second_bms as(
select c.applicant_id
from major_applied_for a inner join major b on a.major_code = b.code and a.preference = 2 and b.name = 'BMS'
inner join application c on a.application_number = c.number ) select fname,
lname from first_cs a inner join second_bms b on a.applicant_id = b.applicant_id
inner join applicant c on a.applicant_id = c.id

MySQL, UNION ALL with SQL_CALC_FOUND_ROWS not working sometimes

I'm having some problems with UNION ALL using SQL_CALC_FOUND_ROWS in MySQL, InnoDB. First let me show a simple database schema to explain what's going on...
Database Schema
Media Table
media_id title
-------------------------------------
1 Empire of the Sun
Genre Pattern Table
genre_id name
-------------------------------------
1 Action
2 Adventure
Locale Table
locale_id code
-------------------------------------
1 en_US
2 pt_BR
3 fr_FR
Genre Translations Table
genre_id locale translation
-------------------------------------
1 1 Action
1 2 Ação
2 1 Adventure
2 2 Aventura
Media Genres Table
media_id genre_id
-------------------------------------
1 1
1 2
Now it's simple: I need to return a genre name compatible with user locale. Let's suppose that user locale is pt_BR. To I get results I use the follow SQL:
select gt.name
from media_genres mg
inner join genre_translation gt on (mg.genre_id = gt.genre_id)
where (mg.media_id = 1 and gt.locale_id = 2)
It returns:
name
-------------------------------------
Ação
Aventura
But, now, let's suppose that user locale is fr_FR. There's no translation for fr_FR, right? The solution I found was use a UNION ALL with SQL_CALC_FOUND_ROWS, then I use the following SQL:
select SQL_CALC_FOUND_ROWS gt.name
from media_genres mg
inner join genre_translation gt on (mg.genre_id = gt.genre_id)
where (mg.media_id = 1 and gt.locale_id = 3)
UNION ALL
select gt.name
from media_genres mg
inner join genre_translation gt on (mg.genre_id = gt.genre_id)
where FOUND_ROWS() = 0 and (mg.media_id = 1 and gt.locale_id = 1)
If there's no found rows for locale_id = 3 and media_id = 1, then I'll get the results for locale_id = 1 (default) and media_id = 1.
The problem is: the statement sometimes return right data and sometimes return no data.
And my main question: why is this happening?
The way to accomplish this is by using LEFT JOIN to join with the translation table, and then use IFNULL to supply a default when there's no match.
SELECT mg.genre_id, IFNULL(gt2.name, gt1.name) AS name
FROM media_genres AS mg
JOIN genre_translation AS gt1 ON mg.genre_id = gt.genre_id AND gt.locale_id = 1
LEFT JOIN genre_translation AS gt2 ON mg.genre_id = gt.genre_id AND gt.locale_id = 3
WHERE mg.media_id = 1

Mysql query to filter result

I have 2 tables
TBL 1: property TBL 2: property_detail
--------------------- --------------------------------------
Id Name status property_id param value
--------------------- --------------------------------------
1 X 1 1 parking two-wheeler
2 Y 1 1 furnishing furnished
3 Z 0 2 parking car-parking
4 A 1 2 furnishing semi-furnished
5 B 1 3 furnishing furnished
6 C 0 4 parking car-parking
"property_id" column in "property_detail" is foreign key of "Id" column in "property"
I want search result for status=1 and (param="parking" and value="car-parking") and (param="furnishing" and value="furnished")
From above Example table, the result will be
Result
-------------
id name
-------------
2 Y
How to achieve this?
you can get your desired result set by using join twice with details table
select p.*
from property p
join property_detail d on (p.Id = d.property_id)
join property_detail d1 on (p.Id = d1.property_id)
where p.status=1
and d.param='parking' and d.value='car-parking'
and d1.param='furnishing' and d1.value='semi-furnished';
Another way you can also use below query using having clause and sum function
select p.*
from property p
join property_detail d on (p.Id = d.property_id)
where p.status=1
group by p.Id
having sum(param="parking" and value="car-parking")
and sum(param="furnishing" and value="semi-furnished")
DEMO
SELECT property.id, property.name
FROM property INNER JOIN property_detail
ON property.id = property_detail.property_id
WHERE
(`param`="parking" AND `value`="car-parking")
AND
(`param`="furnishing" AND `value`="furnished")
AND status = 1;
can you try this one? I'm not sure though.. but it'll give you an idea.

MySQL how to select multiple attributes from a Cartesian product?

I'm trying to get multiple attributes (e.g bedrooms, bathrooms, etc) from a few tables yes I can only seem to get one attribute with my current query. What am I missing?
What I am ultimately trying to find is property_id's with 2 bathrooms and 2 bedrooms. In this case, my desired results are property id's 1 and 4.
Here's my example on sqlfiddle
Example tables:
property
--------
id
1
2
3
4
attribute
---------
id name
1 bedrooms
2 bathrooms
attribute_value
---------------------
id attribute_id value
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 2 3
property_attributes
------------------------------
property_id attribute_value_id
1 2
1 5
2 2
2 4
3 1
3 4
4 2
4 5
This query can produce the results I want if I only want to see a query based on single attribute:
SELECT p.property_id
FROM property p
INNER JOIN property_attribute pa ON p.property_id = pa.property_id
INNER JOIN property_area pc ON p.property_id = pc.property_id
WHERE pa.attribute_value_id
IN (
SELECT av.attribute_value_id
FROM attribute_value av
INNER JOIN attribute a ON av.attribute_id = a.attribute_id
WHERE a.name like 'bedrooms' AND av.value like '2')
But what must I do to get results with more attributes (e.g. WHERE a.name like 'bathrooms' AND av.value like '2')? If I add another subquery in the main where clause, it doesn't return any results.
/// EDIT ///
here is the solution that worked for me if anyone else winds up in such a situation:
SELECT p.property_id
FROM property p
INNER JOIN property_attribute pa ON p.property_id = pa.property_id
INNER JOIN property_attribute pa2 ON p.property_id = pa2.property_id
INNER JOIN property_attribute pa3 ON p.property_id = pa3.property_id
WHERE pa.attribute_value_id = 2
AND pa2.attribute_value_id = 5
AND pa3.attribute_value_id = 7
This makes usage of a self-join.
You have an awful lot of indirection in your schema. Is there any particular point why you need the property_attribute table? Do you expect a single attribute value to be shared by many properties?
In any case, here is the query for you. Very much in the spirit of the two possible duplicates I mentioned above.
SELECT property.property_id,
bedrooms.value AS bedrooms,
bathrooms.value AS bathrooms
FROM property,
attribute AS bedrooms_attr,
attribute_value AS bedrooms,
property_attribute AS bedrooms_prop,
attribute AS bathrooms_attr,
attribute_value AS bathrooms,
property_attribute AS bathrooms_prop
WHERE bedrooms_attr.name = 'bedrooms'
AND bedrooms.attribute_id = bedrooms_attr.attribute_id
AND bedrooms.attribute_value_id = bedrooms_prop.attribute_value_id
AND bedrooms_prop.property_id = property.property_id
AND bedrooms.value = 2
AND bathrooms_attr.name = 'bathrooms'
AND bathrooms.attribute_id = bathrooms_attr.attribute_id
AND bathrooms.attribute_value_id = bathrooms_prop.attribute_value_id
AND bathrooms_prop.property_id = property.property_id
AND bathrooms.value = 2
Thanks for providing a fiddle with data to play with.

JOIN two tables while grouping by an index and maching for multiple foreign ids

I have the 3 Following Tables:
objects:
ObjectID ObjectDescription
1 "first"
2 "second"
attributes:
AttributeID AttributeDescription
1 "att1"
2 "att2"
3 "att3"
4 "att4"
attributelink:
AttributeID ObjectID
1 1
2 1
4 1
Now my question: I want now have some attributes selected and want to know, which Object has all my selected Attributes. I've tried the following:
SELECT * FROM `objects`
INNER JOIN `attributelink`
ON `objects`.`ObjectID` = `attributelink`.`ObjectID`
WHERE `attributelink`.`AttributeID` =1 AND `attributelink`.`AttributeID` =2
GROUP BY `objects`.`ObjectID`
That obviously doesn't work, because one row can't have 2 AttributeIDs, but how can I archieve this?
You have to join on the attributelink table once for each selected attribute you want to check for:
SELECT o.ObjectID
FROM objects o
INNER JOIN attributelink a1 ON o.ObjectID = a1.ObjectID AND a1.AttributeID = 1
INNER JOIN attributelink a2 ON o.ObjectID = a2.ObjectID AND a2.AttributeID = 2
GROUP BY o.ObjectID
Your test data doesn't show a whole lot about whether it works or not, but FWIW, here's the sqlfiddle.
Another way to do it is to use COUNT DISTINCT with HAVING and GROUP BY (sqlfiddle):
SELECT o.ObjectID
FROM objects o
INNER JOIN attributelink a ON o.ObjectID = a.ObjectID
WHERE a.AttributeID IN (1,2) --here you filter the rows on the attributes to test
GROUP BY o.ObjectID
HAVING COUNT(DISTINCT(a.AttributeID)) = 2 --# of attributes, means "having ALL"