get all the tables within a date range - php

I have many weekly backup tables of the same structure and columns but with different names containing some user-specific information like this.
user_details
user_details_20211126
user_details_20211119
user_details_20211112
and so on....
Now I want to find the tables within a date range for example: If I choose the date range of 2021-11-20 to 2021-11-13 then the tables fetched would be user_details, user_details_20211126, user_details_20211119 for using them in a query containing union operation on all the fetched tables.
Any idea on how to do that?

As already commented, what an awful idea ... you shouldn't be doing it that way. One table with a DATE datatype column should by the way to do it. I suggest you switch to it - the sooner, the better.
Meanwhile - although you didn't name database you use & I'm using Oracle - here's what you'll probably have to do, regardless of the database: some kind of dynamic SQL as you have to "dynamically" compose the SELECT statement, using only tables that satisfy the condition. As you have to fetch their names from the data dictionary, you don't have many options but - as I said - dynamic SQL.
OK, here you go.
Setting date format (you don't have to do that):
SQL> alter session set nls_date_format = 'dd.mm.yyyy';
Session altered.
Tables whose names are user_details_something:
SQL> select table_name
2 from user_tables
3 where table_name like 'USER_DETAILS%'
4 order by table_name;
TABLE_NAME
------------------------------
USER_DETAILS
USER_DETAILS_20211126
USER_DETAILS_20211127
USER_DETAILS_20211128
How to select only tables whose name contains date that is between desired values?
query data dictionary (in Oracle, that's user_tables)
extract the DATE part of their names (I chose regexp_substr function; you'd use any you find appropriate)
convert extracted substring into a valid date value (using TO_DATE function)
Therefore:
SQL> select table_name
2 from user_tables
3 where table_name like 'USER_DETAILS%'
4 and to_date(regexp_substr(table_name, '\d+$'), 'yyyymmdd')
5 between date '2021-11-26' and date '2021-11-27';
TABLE_NAME
------------------------------
USER_DETAILS_20211126
USER_DETAILS_20211127
OK; two tables between 26.11.2021 and 27.11.2021 (I didn't feel like creating more of them).
The second part of the job is to actually fetch data from those tables. Here's a function that accepts date period as parameters and returns ref cursor (you can choose something else, of course). Read comments within code:
SQL> create or replace function f_test(par_date_from in date,
2 par_date_to in date)
3 return sys_refcursor
4 is
5 l_str varchar2(1000); -- contains the whole SELECT statement
6 rc sys_refcursor;
7 begin
8 -- loop through all tables whose names satisfy the condition
9 for cur_r in
10 (select table_name
11 from user_tables
12 where table_name like 'USER_DETAILS%'
13 and to_date(regexp_substr(table_name, '\d+$'), 'yyyymmdd')
14 between par_date_from and par_date_to
15 ) loop
16 -- compose a SELECT statement
17 l_str := l_str ||
18 'select ename, job, datum from ' || cur_r.table_name || ' union all ';
19 end loop;
20
21 -- remove trailing UNION ALL
22 l_str := rtrim(l_str, ' union all');
23
24 -- open and return ref cursor
25 open rc for l_str;
26 return rc;
27 end;
28 /
Function created.
OK, let's try it:
SQL> select f_test(date '2021-11-26', date '2021-11-27') from dual;
F_TEST(DATE'2021-11-
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
ENAME JOB DATUM
---------- --------- ----------
SMITH CLERK 26.11.2021
JONES MANAGER 26.11.2021
SCOTT ANALYST 26.11.2021
ADAMS CLERK 26.11.2021
FORD ANALYST 26.11.2021
ALLEN SALESMAN 27.11.2021
WARD SALESMAN 27.11.2021
MARTIN SALESMAN 27.11.2021
BLAKE MANAGER 27.11.2021
TURNER SALESMAN 27.11.2021
JAMES CLERK 27.11.2021
11 rows selected.
SQL>
It works for me; I hope you won't have to make it "work" at all, but - after you apply what we've already suggested - run a simple
SQL> select * from user_details
2 where datum between date '2021-11-26' and date '2021-11-27';
DEPTNO EMPNO ENAME JOB DATUM
---------- ---------- ---------- --------- ----------
20 7369 SMITH CLERK 26.11.2021
20 7566 JONES MANAGER 26.11.2021
20 7788 SCOTT ANALYST 26.11.2021
20 7876 ADAMS CLERK 26.11.2021
20 7902 FORD ANALYST 26.11.2021
30 7499 ALLEN SALESMAN 27.11.2021
30 7521 WARD SALESMAN 27.11.2021
30 7654 MARTIN SALESMAN 27.11.2021
30 7698 BLAKE MANAGER 27.11.2021
30 7844 TURNER SALESMAN 27.11.2021
30 7900 JAMES CLERK 27.11.2021
11 rows selected.
SQL>
Obviously, my user_details table contains the DATE datatype column and makes everything A LOT simpler.

Related

Get each day of the week as columns MySQL and PHP

I am writing a web application in PHP with MySQL.
I have a table called counts and this is how data is stored in that table:
Table: counts
id counts location_id media_id created_at
--------------------------------------------------
1 50 1 1 2017-03-15
2 30 2 1 2017-03-15
3 80 1 2 2017-03-15
4 20 1 1 2017-03-16
5 100 2 2 2017-03-16
For every unique location_id, media_id and created_at, I store count.
I have another table locations which is like this:
Table: locations
id name
----------------
1 Location 1
2 Location 2
3 Location 3
4 Location 4
5 Location 5
This is the SQL Query I have at the moment:
select sum(counts.count) as views, locations.name as locations, DAYNAME(counts.created_at) AS weekday from `counts` inner join `locations` on `locations`.`id` = `counts`.`location_id` where `counts`.`created_at` between '2016-12-04' and '2016-12-10' group by `weekday`, `counts`.`location_id`;
This is how the data is displayed:
locations weekday views
-----------------------------------
Location 1 Mon 50
Location 1 Tue 30
Location 2 Mon 20
Location 2 Tue 70
I'm creating reports and I would like to run a query such that all the days of the week appear as a column with their corresponding values as the view count for that day of the week. I want something like this:
locations mon tue wed thu fri sat sun
-------------------------------------------------
Location 1 40 60 51 20 40 20 30
Location 2 80 60 100 24 30 10 5
Is the above possible in MySQL or I would have to use PHP to achieve that? If so, how do I go about it?
Any help will be appreciated, thanks.
NB: The sample data is not accurate.
It's possible to achieve this result with MySQL, using conditional aggregation.
The trick is to use a conditional test in an expression in the SELECT list to determine whether to return a value of count.
Something like this:
SELECT l.name AS `locations`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Mon',c.count,0)) AS `mon`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Tue',c.count,0)) AS `tue`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Wed',c.count,0)) AS `wed`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Thu',c.count,0)) AS `thu`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Fri',c.count,0)) AS `fri`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Sat',c.count,0)) AS `sat`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Sun',c.count,0)) AS `sun`
FROM `locations` l
LEFT
JOIN `counts` c
ON c.location_id = l.id
AND c.created_at >= '2016-12-04'
AND c.created_at < '2016-12-04' + INTERVAL 7 DAY
GROUP BY l.name
ORDER BY l.name
NOTE:
With the sample data, there are two rows for location_id=1 and created_at='2016-03-15', so this query would return a total of 130 for tue (=50+80), not 50 (as shown in the sample output of the existing query).

Select data from two tables with no join condition

I'd appreciate if someone could help. I have two tables that have no relationship:
Table_1
ID credittype creditamount date time
------------------------------------
1 abc 10 2016-01-18 11:29:59 am
2 def 20 2016-01-20 4:35:58 pm
3 def 20 2016-01-21 4:35:58 pm
Table_2
ID debitetype debiteamount date time
------------------------------------
1 abc 10 2016-01-18 11:29:59 am
2 def 20 2016-01-19 4:35:58 pm
3 def 20 2016-01-21 4:35:58 pm
i just want to display these tables values
like that
credittype creditamount debitetype debiteamount date time
---------------------------------------------------------
abc 10 2016-01-18 11:29:59 am
def 20 2016-01-19 4:35:58 pm
def 20 2016-01-20 4:35:58 pm
i will try this query
select * from Table_1 union select * from Table_2;
i did not get answer any one help me?
Using union only gets distinct values from both tables. Try using "union all" to return all values. Refer to http://www.w3schools.com/sql/sql_union.asp.
Note , joining 2 table that don't have any condition not good , and it discovered that you don't design your database structure very well.
so , try like this :
select tb1.credittype,tb1.creditamount,tb1.debitetype,tb1.debiteamount,tb1.date,tb1.time from table1,table2
it gives you all record in table one and table two

Multiple tables from two database in mysql using php

I have 2 tables in Mysql db, table 1
serial Remark
-------------------
1 programming in c++
2 OOPS using java
and table 2
Name date code serial
-------------------------------------
Jack 2014-10-07 c++ 1
Jill 2014-10-07 c++ 1
Moos 2014-10-07 c++ 1
Jack 2014-10-08 java 2
Jill 2014-10-08 java 2
I want to generate multiple table using php in HTML,
1.Students in Programming in c++ are
Name date
-------------------
Jack 2014-10-07
Jill 2014-10-07
Moos 2014-10-07
2.Students in OOPS using java
Name date
-------------------
Jack 2014-10-08
Jill 2014-10-08
Can someone suggest the query?
Query for case 1:
SELECT name, date from table2 inner join table1 on table2.serial = table1.serial where Remark='programming in c++'
Query for case 2:
SELECT name, date from table2 inner join table1 on table2.serial = table1.serial where Remark='OOPS using java'
or,
Another way:
Query for case 1:
SELECT name, date from table2, table1 where table2.serial = table1.serial and Remark='programming in c++'
Query for case 2:
SELECT name, date from table2, table1 where table2.serial = table1.serial and Remark='OOPS using java'

Php mysql routine for calculating in one table and place results in another table

I need a php routine for my mysql database. I have made an example to illustrate the problem:
Lets say I have a table that registrates customers and how much money they spend. A customer can have more registrations:
Table1:
Name - Amount
Jane - 3
Mark - 4
Sara - 5
Jane - 5
Jane - 6
Sara - 2
I want a routine that goes trough Table1, and finds how much each person has spend. I want the result in Table2, like this:
Table2:
Jane - 14
Mark - 4
Sara - 7
Do you have a solution to this?
insert into table2 select name, sum(amount) from table1 group by name;
SELECT Name, SUM(Amount) FROM Table1 GROUP BY Name

MySQL query problematic

I'm using PHP/MySQL and I have to create a new table from an existing one. Here's the problematic:
Table1:
photo_id email name_to creation_date link
1 foo1#bar.com paul 2012-11-21 link1.com
2 foo2#bar.com mark 2012-11-22 link2.com
3 foo1#bar.com alex 2012-11-23 link3.com
4 foo1#bar.com saul 2012-11-25 link4.com
5 foo1#bar.com john 2012-11-26 link5.com
6 foo2#bar.com math 2012-11-27 link6.com
7 foo3#bar.com fred 2012-11-28 link7.com
In Table1 the email is not unique, it can be repeated several times. Each link is different. With this data, I have to create a new table in which the email is unique with maximum of 3 links if there's more entries of one email (if so I need the data of the 3 latest entries).
So, in this case, Table2 would be like:
email link1 creation_date1 name_to1 link2 creation_date2 name_to2 link3 creation_date3 name_to3
foo1#bar.com link5.com 2012-11-26 john link4.com 2012-11-25 saul link3.com 2012-11-23 alex
foo2#bar.com link6.com 2012-11-27 math link2.com 2012-11-22 mark
foo3#bar.com link7.com 2012-11-28 fred
I know the GROUP_CONCAT feature but it's not really what I need here since the links would all be in the same column. Is it better to make a SELECT * FROM table1 and process the result into PHP arrays and after that create Table2 or a unique MySQL query would do the trick? Or create multiple MySQL tables?
Table1 is over 10 millions rows.
Any advice would be appreciate.
Thanks.
1) select all unique emails.
2) For each email, take the first 3 rows with that email ordered by creation_date descending.
3) Use that data to insert into new table.
Whatchu think?

Categories