tricky mysql query with categories - php

here's my data structure:
category_main
id name
---------------------
1 catmain1
2 catmain2
category_sub
id name id_catmain
---------------------
1 catsub1 1
2 catsub2 1
3 catsub3 2
images
id name catsub
---------------------
1 image1 1
2 image2 1
3 image3 2
4 image4 3
desired output:
id_catmain catmain images_total
--------------------------------------------------
1 catmain1 3
2 catmain2 1
the problem is getting the total amount of images per main category ..
i tried something like (as a view)
select categories.*, group_concat(id) as all_cat from categories group by id_catmain
then querying that view using FIND_IN_SET .. but i think there must be a better way using one query only. any ideas?
thanks

Something along these lines should work I think:
SELECT c.id, c.name, COUNT(*) AS images_total FROM images i
JOIN category_sub cs ON cs.id = i.catsub
JOIN category_main c ON c.id = cs.id_catmain
GROUP BY c.id
What you are basically doing there is tying all the image table's rows to the subcategories they represent, then tying the main categories to the same row through the subcategory id. Then you can simply count all the rows, grouping the amount of counted rows by all the different main category ids.

You can solve this in many ways. One of these would be to use a subquery:
SELECT c.id AS id_catmain, c.name AS catmain,
(SELECT COUNT(i.id) AS totalImages
FROM images i
INNER JOIN category_sub s ON i.catsub = s.id
WHERE s.id_catmain = c.id) as totalImages
FROM category_main c
ORDER BY c.name ASC;
Sample here: http://sqlfiddle.com/#!9/d78e2/5
This is not better than Bun's answer, it's just to say there are other ways of doing this.

Related

MySQL WHERE filter based on subquery in SELECT

I have a table named Records that shows products. I also have a table named Categories that shows the categories for each individual product (if one exists).
The Categories table is structured liked:
id category_id
-- -----------
1 1
1 3
3 1
3 2
5 4
The query I run to pull record ID and category ID(s) is:
SELECT
Records.id,
(SELECT
GROUP_CONCAT(C.category_id)
FROM `Categories` C
WHERE Records.id = C.id) AS 'CategoryName'
FROM
Records
The output will return:
id CategoryName
-- ------------
1 1,3
2 NULL
3 1,2
4 4
5 NULL
I have an area of my website where users can filter records by category. Let's say user wants to filter for category = 1 or 2. I was thinking I just tack on a WHERE FIND_IN_SET(1,CategoryName) OR FIND_IN_SET(2,CategoryName) but this does not work because of the MySQL execution order and CategoryName column does not exist yet.
What is the best way to filter for category_id? The input for categories will be comma separated but I can use PHP to explode() the string to separate them.
You can rewrite the query with a LEFT join of Records to Categories:
SELECT r.id,
GROUP_CONCAT(c.category_id) AS CategoryName
FROM Records r LEFT JOIN Categories c
ON c.id = r.id
GROUP BY r.id
and if you want to use the same query for filtering all you have to do is add at the end a HAVING clause:
HAVING FIND_IN_SET(1, CategoryName) OR FIND_IN_SET(2, CategoryName)
Or, you can filter first and then aggregate:
SELECT r.id,
GROUP_CONCAT(c.category_id) AS CategoryName
FROM Records r INNER JOIN Categories c
ON c.id = r.id
WHERE c.category_id IN (1, 2)
GROUP BY r.id

MySQL Multi-Join Query

I have multiple tables I am trying to grab data from in a single query. I seem to be close to a solution but can not seem to get the data result I am expecting.
Examples of my tables are as follows (fields have been truncated):
Table c
id
name
abbreviation
Table mr (relationship table tat ties tables c and m together by ID)
id
c.id
m.id
Table m
id
Table cnt
id
c.id
Table cmp
id
cnt.id
active
What I WANT is all fields from C, all fields from M where m.id = c.id, all active (active = 1) id's from CMP that match on cnt.id.
My most recent query (after dozens of iterations) is:
SELECT c.id AS id
, c.name AS name
, c.abbreviation AS abbr
, c.active AS active
, c.last_modified AS last_modified
, c.modified_by AS modified_by
, mr.media_id
, mr.related_object_table
, mr.related_object_id
, m.orig_name AS img_name
, m.unique_name AS img_slug
, m.file_type AS confed_file_type
, m.file_size AS file_size
, COUNT('cmp.id') AS comps
FROM confederations AS c
LEFT JOIN media_relationships AS mr
ON mr.related_object_id = c.id
AND mr.related_object_table = 'confederations'
LEFT JOIN media AS m
ON m.id = mr.media_id
INNER JOIN countries AS cnt
ON cnt.confederations_id = c.id
INNER JOIN competitions AS cmp
ON cmp.countries_id = cnt.id
AND cmp.active = 1;
I am not proficient with Joins.
Basically, the result i am expecting is: For each Confederation (table C) I want that confederations name, abbreviation, active status (active), last modified date, modified by; from the Media Relationship table (table MR) I want the image id associated with that confederation so I can use that id to grab the image name and image slug for the confederations primary image from the Media table (M).
Now I also want the total number of Competitions (table CMP) for a given Confederation. Competitions are stored with a Country ID that is tied to the primary key ID of a country in the Countries Table (table CNT). Each Country in table CNT has a Confederations ID. So to get the total number of Competitions per Confederation I am 'trying' to get all Countries within their respective Confederation by CONFEDERATIONS_ID in table CNT, then foreach confederation I want select all the competitions from table CMP with matching COUNTRIES_ID from the group of country id's for that given confederation. (At this point i think i am confusing myself with how to get what i want)
Somehow I am getting the CORRECT NUMBER of competitions, but I am getting duplicate Confederations as results. For Example I am getting something similar to this (assume I have 3 different confederations with 2, 1, and 3 competitions respectively):
Competitions 1 : name 1 | abbreviation 1 | image 1 | total competitions = 2;
Competitions 1 : name 1 | abbreviation 1 | image 1 | total competitions = 1;
Competitions 1 : name 1 | abbreviation 1 | image 1 | total competitions = 3
What am i doing wrong?
Through trial and error, I actually solved this on my own. I came back to post my answer and see Degan's answer, and though it is written differently than mine I think its very close to what I ended up with:
SELECT
cnf.id AS confed_id, cnf.name AS confed_name, cnf.abbreviation AS
confed_abbr, cnf.active AS confed_active, cnf.modified_by AS
confed_mod_by, cnf.last_modified AS confed_last_mod,
COUNT(cnt.id) AS total_countries,
COUNT(cmp.id) AS total_comps,
mr.media_id, mr.related_object_table, mr.related_object_id,
mr.primary_img,
m.orig_name AS img_name, m.unique_name AS img_slug, m.file_type AS file_type
FROM confederations AS cnf
LEFT JOIN media_relationships AS mr
ON mr.related_object_id = cnf.id AND mr.related_object_table = 'confederations'
LEFT JOIN media AS m
ON m.id = mr.media_id
LEFT JOIN countries AS cnt
ON cnt.confederations_id = cnf.id AND cnt.active = 1
LEFT JOIN competitions AS cmp
ON cmp.countries_id = cnt.id AND cmp.active = 1
GROUP BY cnf.id
So farthis seems to be giving me results i can use. I am not certain if my choice of Left Join for all my joins is in fact giving me everything i need (it SEEMS to be) and whether this will omit/add records once the tables get larger. If anyone can point out a problem in my query and my choice of using Left Join as opposed to a combination of LEFT and INNER JOINs as Degan did, that would be helpful.
When aggregating you need to group by.
Perhaps this is close to what you are looking for:
SELECT c.id AS id
, c.name AS name
, c.abbreviation AS abbr
, m.orig_name AS img_name
, SUM('cmp.id') AS comps
FROM confederations AS c
LEFT JOIN media_relationships AS mr
ON mr.related_object_id = c.id
AND mr.related_object_table = 'confederations'
LEFT JOIN media AS m
ON m.id = mr.media_id
INNER JOIN countries AS cnt
ON cnt.confederations_id = c.id
INNER JOIN competitions AS cmp
ON cmp.countries_id = cnt.id
AND cmp.active = 1
GROUP BY c.id AS id
, c.name AS name
, c.abbreviation AS abbr
, m.orig_name AS img_name

php - mysql join three tables and grouping

I have three tables:
products:
id name
1 juice
2 chips
3 water
orders:
id product_id order_id
1 1 special1
2 3 special1
3 2 special1
4 1 special2
5 2 special2
final_orders:
id order_id date
1 special1 25-3-2017
2 special2 25-3-2017
I want to select all products names in every order using order_id to show:
ID: Special1
Date: 25-3-2017
Products List:
juice
water
chips
ID: Special2
Date: 25-3-2017
Products List:
juice
chips
I use this:
$sql = "select * from products,orders where products.id = orders.product_id";
but it doesn't work and show me duplicated results.
thank you.
You need to join with final_orders as well:
SELECT *
FROM final_orders AS f
JOIN orders AS o ON f.order_id = o.order_id
JOIN products AS p ON p.id = o.product_id
ORDER BY f.order_id
To prevent duplication in the output, your loop that prints the output should only show the information from final_orders when it changes. See How can i list has same id data with while loop in PHP?
If you want to see one final order per record in your result set, then you will have to aggregate the products which appear in each order. One option then is the following query which aggregates order products into CSV using MySQL's GROUP_CONCAT():
SELECT t1.order_id,
t1.date,
t2.products
FROM final_orders t1
INNER JOIN
(
SELECT a.order_id, GROUP_CONCAT(b.name) AS products
FROM orders a
INNER JOIN products b
ON a.product_id = b.id
GROUP BY a.order_id
) t2
ON t1.order_id = t2.order_id
Demo here:
Rextester

Finding records in a union - MySQL

I'm probably approaching this the wrong way, but here's the background. I have a table of products and a table of relations between the products - so, for instance, the relationship table might look like this:
ID PRODUCT 1 PRODUCT 2
1 1 2
2 1 3
3 3 4
So, in the above example, product id 1 is related to products 2 & 3, product id 2 is related to 1 and product id 3 is related to 1 & 4 (since the relationship can be in either column 1 or 2)
So, I'm on the product page and want to find the details of products that are related to the current product. My instinct tells me to do a query like this:
SELECT p.* FROM products p
WHERE p.id IN (
(SELECT product_1 AS related FROM relations WHERE product_2 = :this_product)
UNION
(SELECT product_2 AS related FROM relations WHERE product_1 = :this_product)
)
But that gives me a syntax error because of the UNION.
So, am I doing this all wrong and should be taking a completely different approach or have I just made a minor syntax boo-boo with my query?
To get the list of products, you can do something like this:
select (case when :this_product = product_1 then product_2 else product1 end)
from relations r
where :this_product in (product_1, product_2)
Then you can join products back in.
Alternatively, use exists. It is more efficient:
select p.*
from products p
where exists (select 1
from relations r
where r.product_1 = :this_product and p.id = r.product_2
) or
exists (select 1
from relations r
where r.product_2 = :this_product and p.id = r.product_1
);
You need to remove the brackets used around union like below:
SELECT p.* FROM products p
WHERE p.id IN (
(SELECT product_1 AS related FROM relations WHERE product_2 = :this_product
UNION
SELECT product_2 AS related FROM relations WHERE product_1 = :this_product)
)
Check the fiddle here
Below is the example, you can also try this
SELECT p.*,p1.product_1
FROM products p
LEFT JOIN relations as rel
ON p.id = relational_field
WHERE p.id IN ( product_2, product_1 )

mysql multiple COUNT() from multiple tables with LEFT JOIN

I want to show the conclusion of all users.
I have 3 tables.
table post
post_id(index) user_id
1 1
2 3
3 3
4 4
table photo
photo_id(index) user_id
1 2
2 4
3 1
4 1
table video
photo_id(index) user_id
1 4
2 4
3 3
4 3
and in table user
user_id(index) user_name
1 mark
2 tommy
3 john
4 james
in fact, it has more than 4 rows for every tables.
I want the result like this.
id name post photo videos
1 mark 1 2 0
2 tommy 0 1 0
3 john 2 0 2
4 james 1 1 2
5 .. .. .. ..
Code below is SQL that can work correctly but very slow, I will be true appreciated if you help me how it using LEFT JOIN for it. Thanks.
SQL
"select user.*,
(select count(*) from post where post.userid = user.userid) postCount,
(select count(*) from photo where photo.userid = user.userid) photoCount,
(select count(*) from video where video .userid = user.userid) videoCount
from user order by user.id"
(or ORDER BY postCount, photoCount or videoCount ASC or DESC as i want )
I done researched before but no any helped me.
SELECT u.user_id,
u.user_name,
COUNT(DISTINCT p.post_id) AS `postCount`,
COUNT(DISTINCT ph.photo_id) AS `photoCount`,
COUNT(DISTINCT v.video_id) AS `videoCount`
FROM user u
LEFT JOIN post p
ON p.user_id = u.user_id
LEFT JOIN photo ph
ON ph.user_id = u.user_id
LEFT JOIN video v
ON v.user_id = u.user_id
GROUP BY u.user_id
ORDER BY postCount;
Live DEMO
Your method of doing this is quite reasonable. Here is your query:
select user.*,
(select count(*) from post where post.userid = user.userid) as postCount,
(select count(*) from photo where photo.userid = user.userid) as photoCount,
(select count(*) from video where video.userid = user.userid) as videoCount
from user
order by user.id;
For this query, you want the following indexes:
post(userid)
photo(userid)
video(userid)
user(id)
You probably already have the last one, because user.id is probably the primary key of the table.
Note that a left join approach is a bad idea in this case. The three tables -- posts, photos, and videos -- are independent of each other. If a user has five of each, then joining them together would produce 125 intermediate rows. If a user has fifty of each, it would be 125,000 -- a lot of extra processing.
Your answer is probably slow as it is using a correlated sub-query i.e. the sub query is running once for each user_id (unless the optimizer is doing something smart - which shouldn't be counted on).
You could use a left outer join and count or use something temporary like:
SELECT u.user_id,
u.user_name,
ph.user_count AS 'photoCount',
p.user_count AS 'postCount',
v.user_count AS 'videoCount'
FROM user u
INNER JOIN ( SELECT user_id,
COUNT(*) AS user_count
FROM photo
GROUP BY user_id
) ph
ON ph.user_id=u.user_id
INNER JOIN ( SELECT user_id,
COUNT(*) AS user_count
FROM post
GROUP BY user_id
) p
ON p.user_id=u.user_id
INNER JOIN ( SELECT user_id,
COUNT(*) AS user_count
FROM video
GROUP BY user_id
) v
ON v.user_id=u.user_id
There are pros and cons for both (depending on indexes). Always have a look at the query plan (using EXPLAIN for MySQL).

Categories