How to seperate out group concat results - mysql

I am using Group concat in aggregate function in my project to display subcategories of a categories.
This is MYSQL query.
$sql_query = "SELECT TC.category_name, GROUP_CONCAT(TS.sub_category_name ORDER BY TS.sub_category_name) from table_categories as TC
INNER JOIN
table_subcategory_categories as TSC
ON
TSC.category_id = TC.category_id
INNER JOIN
table_subcategories as TS
ON
TS.sub_categories_id = TSC.subcategory_id
GROUP BY TC.category_id
order by TC.category_name";
The Problem is i need to process these subcategories as separate entities. But Because of Group concat they becomes a single entity.
What is the solution for this?
Is there any alternative of Group concat to achieve the same.
Current:
Body Wash <a>Bathing Soap|Shower Gel</a> delete
This delete makes no sense here.
Expecting:
Body Wash <a>Bathing Soap</a> delete
<a>Shower Gel</a> delete

So why not just remove the GROUP_CONCAT...?
$sql_query = "SELECT TC.category_name, TS.sub_category_name
from table_categories as TC
INNER JOIN
table_subcategory_categories as TSC
ON
TSC.category_id = TC.category_id
INNER JOIN
table_subcategories as TS
ON
TS.sub_categories_id = TSC.subcategory_id
order by TC.category_name, TS.sub_category_name";

Try removing the group by:
select TC.category_name, TS.sub_category_name
from table_categories TC INNER JOIN
table_subcategory_categories TSC
ON TSC.category_id = TC.category_id INNER JOIN
table_subcategories TS
ON TS.sub_categories_id = TSC.subcategory_id
order by TC.category_name, TS.sub_category_name;
You are going to get the values in multiple rows. You will also get category_name repeated in each row. That is how SQL result sets work. If you don't want the category repeated, then do something on the application side to get the results you want.

Related

How can I grab all rows from one table, but filter the second table?

I am running a query on a PHP page that will pull all records from one table, INNER JOIN with two other tables and then list all of the results. However on the second table I only want the most recent record.
Here is my query
SELECT * FROM wn_trailer
INNER JOIN (
SELECT id, trailer_id, trailer_status, trailer_assigned, MAX(last_update), trailer_lat, trailer_long
FROM wn_trailer_history
) AS th ON wn_trailer.id = th.trailer_id
INNER JOIN wn_trailer_status ON wn_trailer_status.id = th.trailer_status
INNER JOIN wn_users ON wn_users.id = th.trailer_assigned
ORDER BY trailer_number ASC
The query runs but returns only the first record.
You want an additional JOIN to bring in the data on the last update date. Also, your subquery needs a GROUP BY:
SELECT *
FROM wn_trailer t INNER JOIN
(SELECT trailer_id, MAX(last_update) as max_last_update
FROM wn_trailer_history
GROUP BY trailer_id
) tht
ON t.id = tht.trailer_id INNER JOIN
wn_trailer_history th
ON th.trailer_id = tht.trailer_id AND
th.last_update = tht.max_last_update INNER JOIN
wn_trailer_status ts
ON ts.id = th.trailer_status INNER JOIN
wn_users u
ON u.id = th.trailer_assigned
ORDER BY trailer_number ASC;
I also added table aliases so the query is easier to write and to read.

MYSQL Distinct results from a query

What i'm trying to do is get the DISTINCT results using a MYSQL query:
$sql = "SELECT un.*, co.order_product_quantity AS product_num, cu.first_name, cu.surname, cp.product_name, cp.product_thumbnail AS prod_img, co.order_goods_cost, co.order_delivery_cost, co.order_status as status
FROM (
SELECT DISTINCT order_unique_id AS o_id, order_date
FROM cbs_orders
GROUP BY order_unique_id
) un
INNER JOIN cbs_orders co ON co.order_unique_id = un.o_id
INNER JOIN cbs_users cu ON cu.id = co.order_user_id
INNER JOIN cbs_products cp ON cp.product_id = co.order_product_id
ORDER BY un.order_date DESC LIMIT $start_from, $num_rec_per_page ";
I'm looking to get the DISTINCT order_unique_id from the query, i never wrote the query initially, i thought adding "SELECT DISTINCT order_unique_id" would solve the issue but it still brings back duplicate ids.
cheers for any help guys
Graham
You want to leverage GROUP BY correctly; DISTINCT won't help you in this situation. Additional, I'm pretty sure that sub-select is not needed.
Try this
$sql = "SELECT un.order_unique_id AS o_id, un.order_date,
co.order_product_quantity AS product_num,
cu.first_name, cu.surname, cp.product_name,
cp.product_thumbnail AS prod_img, co.order_goods_cost,
co.order_delivery_cost, co.order_status as status
FROM cbs_orders AS un
INNER JOIN cbs_orders co ON co.order_unique_id = un.o_id
INNER JOIN cbs_users cu ON cu.id = co.order_user_id
INNER JOIN cbs_products cp ON cp.product_id = co.order_product_id
GROUP BY un.order_unique_id
ORDER BY un.order_date DESC
LIMIT $start_from, $num_rec_per_page ";
This might produce odd results, because you are not applying aggregate functions to other columns. You may need to use those to get desired results.
Let me hazard a guess that you want records for only the most recent order. If this is the case, then you can do what you want, by properly aggregating the data:
SELECT un.*, co.order_product_quantity AS product_num, cu.first_name,
cu.surname, cp.product_name, cp.product_thumbnail AS prod_img,
co.order_goods_cost, co.order_delivery_cost, co.order_status as status
FROM (SELECT order_unique_id AS o_id, max(order_date) as order_date
FROM cbs_orders
GROUP BY order_unique_id
) un INNER JOIN
cbs_orders co
ON co.order_unique_id = un.o_id INNER JOIN
cbs_users cu
ON cu.id = co.order_user_id INNER JOIN
cbs_products cp
ON cp.product_id = co.order_product_id
ORDER BY un.order_date DESC
LIMIT $start_from, $num_rec_per_page;
If you want only one row per order, then you need to figure out what to do with the products. In my opinion, this interpretation is so different from your current question that you should ask another question, providing sample data and desired results.

Grouping by multiple columns in SQL

I am trying to bring through the site.Site_Name, for each hive.hiveno and it's max(hiverdg.invdate). Running the code below doesn't work because site.Site_Name is not aggrigated. If I add site.Site_Name to the Group By, the code runs, but the ouput displays the results repeated, once for each site.Site_Name
select site.Site_Name ,hive.hiveno, max(hiverdg.invdate)
from hiverdg
inner join hive
on hiveRdg.hive_Link = hive.hive_Link
inner join Customer
on customer.Customer_Link = hive.Customer_Link
inner join site
on site.Customer_Link = customer.Customer_Link
where
(hiverdg.xtype = 'N'
and customer.CustomerName = 'Cust1')
or
(hiverdg.xtype = 'A'
and customer.CustomerName = 'Cust1')
group by hive.hiveno
The easiest way to do this, with your query, is the substring_index()/group_concat() trick:
select substring_index(group_concat(s.Site_Name order by rdg.invdate desc separator '|'
), '|', 1
) as SiteName,
h.hiveno, max(rdg.invdate)
from hiverdg rdg inner join
hive h
on rdg.hive_Link = h.hive_Link inner join
Customer c
on c.Customer_Link = h.Customer_Link inner join
site s
on s.Customer_Link = c.Customer_Link
where rdg.xtype in ('N', 'A') and c.CustomerName = 'Cust1')
group by h.hiveno;
I also made the following changes to your query:
Introduced table aliases, to make the query easier to write and to read.
Changed the where to use in, simplifying the logic.

MYSQL Inner join for three to four tables

Please I need to figure out what I am doing wrong. I created this inner join code for mysql. it works but it gives me repeated values like repeating a particular row twice or categoryid twice. each of the tables(users,paymentnotification,monthlyreturns) has the categoryid used to check and display the username(users.pname) from the user table, then check and display those that have made payment from the monthly returns and payment table using the categoryid.
$r="SELECT monthlyreturns.categoryid, monthlyreturns.month, monthlyreturns.quarter, monthlyreturns.year,paymentnotification.amount, users.pname, monthlyreturns.ototal, paymentnotification.payee, status
FROM paymentnotification
INNER JOIN (monthlyreturns INNER JOIN users ON monthlyreturns.categoryid=users.categoryid)
ON monthlyreturns.categoryid=paymentnotification.categoryid
ORDER BY monthlyreturns.categoryid DESC";
I think the query you want is more like this:
SELECT b.categoryid, b.month, b.quarter, b.year, a.amount, c.pname, b.ototal, a.payee, status
FROM paymentnotification a
INNER JOIN monthlyreturns b
ON a.categoryid = b.categoryid
INNER JOIN users c
ON b.categoryid = c.categoryid
ORDER BY b.categoryid DESC
The way you are doing the correlations doesn't seem clear and may cause problems. Try this one out and see what happens. If its still doing duplicates, perhaps the nature of the data require further filtering.
Assuming I understand what you're trying to do, you are not joining your tables properly. Try joining one at a time
SELECT DISTINCT monthlyreturns.categoryid, monthlyreturns.month, monthlyreturns.quarter, monthlyreturns.year,paym entnotification.amount, users.pname, monthlyreturns.ototal, paymentnotification.payee, status
FROM paymentnotification
INNER JOIN monthlyreturns
ON paymentnotification.categoryid = monthlyreturns.categoryid
INNER JOIN users
ON monthlyreturns.categoryid = users.categoryid
ORDER BY monthlyreturns.categoryid DESC
I don't see any problem.. I get 4 result rows: check this fiddle http://sqlfiddle.com/#!2/165a22/5
this is the query I used:
SELECT m.categoryid, m.month, m.quarter, m.year,p.amount, u.pname, m.ototal, p.payee, m.status
FROM paymentnotification p JOIN monthlyreturns m ON p.categoryid = m.categoryid
JOIN users u ON u.categoryid = m.categoryid
ORDER BY m.categoryid DESC
there are no duplicated rows, just "unique" rows if you consider every column you choose.
Hope it helps
SELECT M.categoryid, M.month, M.quarter, M.year, M.ototal,
P.amount, P.payee, P.status,
U.pname
FROM paymentnotification AS P
INNER JOIN monthlyreturns AS M ON P.categoryid = M.categoryid
INNER JOIN users AS U ON M.categoryid = U.categoryid
ORDER BY M.categoryid DESC

Multiple Joins Mysql Doubles SUM values

Im trying to make a a query, but its doubling the Sum values
SELECT
cidades.id AS id,
cidades.name AS municipio,
Sum(conjuntos.n_uhs) AS uh,
programas.id AS programa,
conjuntos.name
FROM
conjuntos
Inner Join conjuntos_programas ON conjuntos_programas.conjunto_id = conjuntos.id
Inner Join programas ON programas.id = conjuntos_programas.programa_id
Inner Join cidades ON conjuntos.cidade_id = cidades.id
WHERE
conjuntos.situation_id = 2
GROUP BY
conjuntos.cidade_id
ORDER BY
municipio ASC
You've got duplicate rows, you can check this by removing the group by and the SUM(... from your query.
Change the query as follows and tell me if that fixes to problem.
SELECT DISTINCT
cidades.id AS id,
cidades.name AS municipio,
SUM(conjuntos.n_uhs) AS uh,
programas.id AS programa,
conjuntos.name
FROM conjuntos
INNER JOIN conjuntos_programas ON conjuntos_programas.conjunto_id = conjuntos.id
INNER JOIN programas ON programas.id = conjuntos_programas.programa_id
INNER JOIN cidades ON conjuntos.cidade_id = cidades.id
WHERE conjuntos.situation_id = 2
GROUP BY conjuntos.cidade_id
ORDER BY municipio ASC
It sounds like you have a one to many relationship between two or more of your tables to be doing this. Try doing a SELECT * and start debugging your query to see where it is duplicating the rows.