I'm stuck forming a MySQL query. I have 6 tables with similar columns. Before you ask they need to be updated separately and deleted; together with the quantity of the data.
So to get the sum from multiple tables, I use SELECT SUM(x) FROM (SELECT COUNT(value) as x etc)
To get one unique id I use DISTINCT(value). Now I need to combine them into a 2 column query, so I have a unique value and count.
My data looks like this for example form 1 table (multiply by 6):
till_no | fruit | vegetables
123 | apple | null
123 | apple | carrot
125 | apple | pear
124 | apple | null
What I want is 123|2, 124|1, 125|1
SELECT DISTINCT(y), SUM(a) FROM (
(SELECT till_no as y, (SELECT COUNT(till_no) FROM Shop1) as a FROM Shop1 c)
UNION (SELECT till_no as y, (SELECT COUNT(_till_no) FROM Shop2)
as a FROM Shop2 c)
) multipleTables
There is no need to use DISTINCT. GROUP BY clause will take of that on your behalf. You can try below query -
SELECT CONCAT(y, COUNT(y))
FROM (SELECT till_no as y FROM Shop1
UNION
SELECT till_no as y FROM Shop2
UNION
SELECT till_no as y FROM Shop3
UNION
SELECT till_no as y FROM Shop4
UNION
SELECT till_no as y FROM Shop5
UNION
SELECT till_no as y FROM Shop6) multiple tables
GROUP BY y
Ankit put me on the right path.
The solution is:
SELECT z, SUM(y)
FROM (SELECT ea as z, COUNT(ea) as y FROM table1 GROUP BY ea
UNION
SELECT ea as z, COUNT(ea) as y FROM table2 GROUP BY ea
UNION
SELECT ea as z, COUNT(ea) as y FROM table3 GROUP BY ea
UNION
SELECT ea as z, COUNT(ea) as y FROM table4 GROUP BY ea
UNION
SELECT ea as z, COUNT(ea) as y FROM table5 GROUP BY ea
UNION
SELECT ea as z, COUNT(ea) as y FROM table6 GROUP BY ea)
multipletables
GROUP BY y
The trick to solving the solution is to break it into small steps... logically 1+1 sure beats 47+126
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.