Join table values If record exist MySQL - mysql

I need join values from my products table only when record in changes table exist, on other ways get return only from products table, I trying use LEFT JOIN for it but doing something wrong. Also tables changes and products have same structure
SELECT
product.*,
parent.name,
parent.ignored,
child.name,
child.ignored,
changes.*
FROM
products AS product
inner join parent_cat AS parent on product.parent_id = parent.ID
inner join child_cat AS child on product.category_id = child.ID
left join changes AS changes on changes.product_id = product.SKURcrd
WHERE
product.slug = 'some slug'
Returned data looks like:
{#389 ▼
+"parent_id": 3
+"category_id": 142
+"product_id": null
+"slug": "some slug"
+"SKURcrd": "301832"
+"product_name": null
+"product_name_revert": "1911 AIR"
}
Tables Structure looks like (schematic):
------------------------- ----------------------------
SKURcrd | product_name product_id | product_name
------------------------- ----------------------------

Two ways you can do that, either use INNER JOIN to changes or a where clause like where changes. produc_id is not null... like below:
SELECT
product.*,
parent.name,
parent.ignored,
child.name,
child.ignored,
changes.*
FROM
products AS product
inner join parent_cat AS parent on product.parent_id = parent.ID
inner join child_cat AS child on product.category_id = child.ID
left join changes AS changes on changes.product_id = product.SKURcrd
WHERE
product.slug = 'some slug' and changes.product_id is not null

Related

How to handle SQL joins if missing rows on particular table exist

SELECT
fromData.name as fromname, toData.name as toName, prodData.prodname,
t1.`from_id`, t1.`to_id` , t1.`product_id` , t1.`title`, t1.`message`, t1.`senttime` , t1.`readstatus`, t1.`responded`, t1.`merchanthidden`
FROM `inquiries` as t1
INNER JOIN users as fromData on t1.from_id = fromData.id
INNER JOIN users as toData on t1.to_id = toData.id
INNER JOIN products as prodData on t1.product_id = prodData.id
WHERE t1.id=13
Above query joins 3 tables (inquiries, users, products) together and gets data from each table.
Sometimes it is possible that items in the 'products' table get deleted. Trying to join products table by a deleted product id will fail the query.
Is there a way that I can assign 'prodData.prodname' a default value and execute query without failing in case of a missing item in products table ?
Why don't use left join insted of inner join ,
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match.
SELECT
fromData.name as fromname, toData.name as toName, prodData.prodname,
t1.`from_id`, t1.`to_id` , t1.`product_id` , t1.`title`, t1.`message`, t1.`senttime` , t1.`readstatus`, t1.`responded`, t1.`merchanthidden`
FROM `inquiries` as t1
INNER JOIN users as fromData on t1.from_id = fromData.id
INNER JOIN users as toData on t1.to_id = toData.id
LEFT JOIN products as prodData on t1.product_id = prodData.id
WHERE t1.id=13

Inner Join returning no results

I need to get rows out from article and users table when the slug appears in my highlight table.
Highlight Table
id | slug
1 blue
2 green
Article Table
id | slug | title
1 blue
2 pink
User Table
id | slug | name
1 blue
2 green
3 brown
Heres my query:
SELECT slug from highlight_table
INNER JOIN article_table ON highlight_table.slug = article_table.slug
INNER JOIN user_table ON highlight_table.slug = user_table.slug
I would hope to get id 1 from article table and id 1 and 2 from users table.
The issue is Im getting nothing back from the query.
The query has an error because your SELECT slug is ambiguous. Your column slug appears in all of your tables so MySQL doesn't know which column to return. You need to do
SELECT `highlight_table`.`slug` from `highlight_table`
This will tell MySQL to only return the slug column from the highlight_table.
You should then only get 1 row which is blue, because blue exists in all three tables. Changing to LEFT JOIN for both article and user tables would get you 2 results back (green and blue) as INNER JOIN basically works as an AND and LEFT JOIN works more like an OR
Update!
Based on the final lot of information here is a query that does work:
SELECT highlight.slug from highlight
LEFT JOIN article ON highlight.slug = article.slug
LEFT JOIN user ON highlight.slug = user.slug
WHERE
article.slug IS NOT NULL OR user.slug IS NOT NULL
Another example of doing this:
SELECT `highlight`.`slug` from `highlight`
WHERE `highlight`.`slug` IN (SELECT `user`.`slug` FROM `user` UNION SELECT `article`.`slug` FROM `article`)
OR
SELECT `highlight`.`slug` from `highlight`
INNER JOIN (SELECT `user`.`slug` FROM `user` UNION SELECT `article`.`slug` FROM `article`) AS `allslugs` ON `highlight`.`slug` = `allslugs`.`slug`
Another update, I call this one "fun with joins"
SELECT `highlight`.`slug` from `highlight`
RIGHT JOIN `user` ON `highlight`.`slug` = `user`.`slug`
LEFT JOIN `article` ON `highlight`.`slug` = `article`.`slug`
WHERE
`highlight`.`slug` IS NOT NULL
Try changing your query to qualify the column name in select list
SELECT h.`slug` from HighlightTable h
INNER JOIN ArticleTable a ON h.`slug` = a.`slug`
INNER JOIN UserTable u ON h.`slug` = u.`slug`;
Can't reproduce the issue. See This Fiddle
per your latest comment you need a LEFT JOIN query like
SELECT h.`slug` from HighlightTable h
LEFT JOIN ArticleTable a ON h.`slug` = a.`slug`
LEFT JOIN UserTable u ON h.`slug` = u.`slug`;
Then do a separate JOIN and UNION the result set
SELECT h.`slug` from HighlightTable h
INNER JOIN ArticleTable a ON h.`slug` = a.`slug`
UNION
SELECT h.`slug` from HighlightTable h
INNER JOIN UserTable u ON h.`slug` = u.`slug`;

use multiple results of a query within the query with joins

I have some tables in my database, three main ones and one that holds the many-to-many relations.
1. Student (student_id, student_name)
2. Sport (sport_id, sport_name)
3. Departm (depart_id, depart_name)
4. Sch (sch_id, sch_name)
5. StudSport(relationid, studendid, sportid, departid, schid)
What I want to do is e.g. retrieve the name of the department based on the relations when I know the id. I can get the ids like this:
SELECT departid, schid from studsport
inner join Student on student_id = studentid
inner join Sport on sport_id = sportid
where student_id = 1 and sport_id=2
but I want to get the names of the department and the Sch from their corresponding tables, and I dont know how to do that.
As you don't select anything from Student or Sport, you can remove the corresponding inner joins.
SELECT d.depart_name, sch.sch_name FROM StudSport s
INNER JOIN Sch sch ON s.schid = sch.sch_id
INNER JOIN Departm d ON s.departid = d.depart_id
WHERE s.studendid = 1 AND s.sportid = 2
Something like this???
select sch.sch_nam, departm.depart_name,
-- what you have already --
Left outer Join StudSport on Student.student_id = Studsport.studentid and Sport.sport_id = StudSport.sportid
left outer Join Sch on StudSport.schid = Sch.sch_id
left outer join Departm on studsport.depart_id = studsport.departid
This is untested, a fiddle makes it much easier to give answers because of that.
EDIT - I misread your original query - before the downvotes start to rain - fixing it right now.
The way you should use LEFT OUTER and INNER joins is how the data is meant (again, a fiddle will normally be usefull) but it's just a couple of joins from what you have i guess:
select *
from studsport
join student on studsport.studentid = student.student_id
join sport on studsport.sportid = sport.sport_id
left outer Join Sch on StudSport.schid = Sch.sch_id
left outer join Departm on studsport.depart_id = studsport.departid
where student_id = 1 and sport_id=2

MySQL Left Join With And Condition To Same Column

I have tables like this:
tbl_product
===========
product_id (PK)
tbl_product_attribute
=====================
pro_attr_id (PK)
pro_attr_pro_id (FK to tbl_product)
pro_attr_attr_opt_id(FK to tbl_attribute_option)
Now, I would like query Products which have 2 attributes in the tbl_product_attribute.
Example like :
SELECT "p".*
FROM "tbl_omx_product" "p"
LEFT JOIN "tbl_omx_product_attribute" "proAttr" ON "proAttr".pro_attr_pro_id = p.product_id
WHERE
(pro_attr_attr_opt_id LIKE '%1759%' ) AND
(pro_attr_attr_opt_id LIKE '%1776%' )
GROUP BY "p"."product_id";
So I'd like to get Products that has exactly 2 values at tbl_omx_product_attribute, which is 1759 & 1776.
But query like above won't show any result unless I use relation OR instead of AND.
The question what is the query to retrieve Products that have 2 values at the tbl_product_attribute ? thank you
Maybe I misunderstood you, but if you want the product to have both attribute options you can query:
SELECT "p".*
FROM "tbl_omx_product" "p"
JOIN "tbl_omx_product_attribute" "proAttr1"
ON "proAttr1".pro_attr_pro_id = p.product_id
AND "proAttr1".pro_attr_attr_opt_id LIKE '%1759%'
JOIN "tbl_omx_product_attribute" "proAttr2"
ON "proAttr2".pro_attr_pro_id = p.product_id
AND "proAttr2".pro_attr_attr_opt_id LIKE '%1776%'
To get products which have two attributes:
SELECT p.*
FROM tbl_omx_product p
LEFT JOIN tbl_omx_product_attribute proAttr ON proAttr.pro_attr_pro_id = p.product_id
GROUP BY p.product_id
having count(*)=2;
You can filter data as per your required output by just adding where clause.
You can try this:
SELECT p.*
FROM tbl_omx_product AS p
LEFT JOIN tbl_omx_product_attribute AS proAttr ON p.product_id = proAttr.pro_attr_pro_id
WHERE
(pro_attr_attr_opt_id LIKE '%1759%' ) AND
(pro_attr_attr_opt_id LIKE '%1776%' )
GROUP BY p.product_id;

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