I used a little MySQL years ago; now I forgotten a lot and I am lost.
Info: MySQL version 5.7.44 – PHP version 8.1.25
What I want to achieve should be simple: I have a DB with 2 tables [Components and Types in my example); they share the IDtype. This is a simple example:
Tables:
Components [Code, Qty, IDtype]:
Code10, 2, 1
Code20, 10, 2
Code30, 5, 1
Code40, 3, 2
Code50, 7, 1
---
Types [Type, IDtype]:
Standard, 1
Special, 2
---
I want to obtain this result::
[Standard, 3] Code10, Code30, Code50
[Special, 2] Code20, Code40
Which is: the Type name and the number of retrieved records, followed by the list of extracted records
I tried without success several queries, the last one is:
$query = "SELECT * FROM Components
WHERE Components.IDtype = ALL (SELECT Types.IDtype FROM Types)";
This does not return anything.
Even this one that I found in another post does not do the job:
SELECT `KEY`, GROUP_CONCAT(Val SEPARATOR ",") as vals
from table group by `KEY`;
Moreover, admitted that my last query is correct how reported I do not understand how to get the name and record count from the Types table since I only select the IDtype, not the whole record.
Thanks
2
Answers
Thanks Amit, I tried your query but it gives me an error. This is my query (translated in Italian using the real names) and the error I get:
Your fiddle works nicely even if there are a couple of points that I do not understand:
You used c as an alias for Components and t for Types, right? If so, I should write ?
Strange syntax and anyway this does not change anything.
You can use SQL queries with a combination of joins and grouping to aggregate the data from the
Components
andTypes
tables based on theIDtype
column.See this db<>fiddle.