I'm using MySQL v.5.0.77 and I was wondering if it is possible to count the number of tables in a database. I have done a lot of research and am unable to find a way to do this that is not depreciated.
For each user that signs up I had generated a table in a database for them. And now I am trying to get a live count of those tables, if that makes sense. Is this a logical way of storing user information? I am unable to programmatically create entire databases on my server.
You can do a query to information_schema.tables
SELECT COUNT(*) FROM information_schema.TABLES
WHERE TABLE_SCHEMA='$database_name';
You could do it like this:
SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='YOUR_DB_NAME_HERE'
http://dev.mysql.com/doc/refman/5.0/en/information-schema.html
For each user that signs up I had generated a table in a database for them. And now I am trying to get a live count of those tables, if that makes sense. Is this a logical way of storing user information?
If you're creating a separate table for each and every user then probably not. There are better ways to store the data and relationships, which can be more complicated to learn but will provide far more flexibility, abilities, and scalability later on.
I think you're probably trying to reproduce the functionality of the database in your programming e.g. getting a list of users would require you to run a query on every single user table.
I recommend you take a look at database design and database normalization (try to focus on the concept of how best to store data first without getting bogged down in the specifics).
I don't know if this is slower than ajreal's answer but I've been using :
$sql = "SHOW TABLES";
$res = mysql_query($sql);
$num_tables = mysql_num_rows($res);
Open Terminal, and type use myDB, then show tables;
It will gives you total tables name and last line as total tables count 47 rows in set (0.00 sec)
Or type below query
SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='myDB'
Related
I have a logging database where I archive every week new tables like :
log_20170823
log_20170816
log_20170809
log_20170802
log_20170726
How can I easily merge all these tables into 1 table in another server (archived) for query simplicity. The current procedures all uses the "log" table.
I mean, I know I can use "UNION" but I want this to be dynamic, because the archiving of the table itself is dynamic, meaning I won't know the name of the archived tables necessarily.
So far I was thinking on doing a
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME LIKE 'log_%'
And then save result into an array, foreach the array and build a dynamic string with the names of the tables I'd need to join/union/merge.
Is there any other way directly in mySQL to do so?
My way seams sketchy and I'm worrying about the performance of it.
Thanks in advance.
related to another question that no body answerd.
in another question that i asked before some person helped me but now i am stuck in another situation.
ok now i want to know is there any way in some table we use from two seperate engine like 2 column uid and username has myisam engine and lastlogin which is a timestamp has a memory engine in use.
because i thought its not possible i tryed to make a table onlineusers(MEMORY ENGINE) in database with two columns one was uid and another one was lastlogin and then when user wants to login i check database like this and insert if user not exist
$myquery = mysql_query('SELECT COUNT(1) FROM `onlineusers` WHERE uid="'. $row['uid'] . '"');
if(mysql_result($myquery,0) == 0){
$data['uid'] = $row['uid'];
$db->insert("onlineusers",$data);
}else{
updateStatus($row['uid']);
}
and update status function is like this
function updateStatus($uid){
$db = DATABASE::obtain();
$query = mysql_query("UPDATE `onlineusers` set `lastvisit`=now() WHERE uid='".$db->escape($uid)."'");
}
but when i thought about this i figured it out when we restart our server then table of onlineusers will be empty and what will happen for users with cookies set logged in?
then i have to change update function to use two seperate query first query check if uid exist in onlineuses then if not we will insert into it or if exist we have to update timestamp..
now i have another question to ask.
using this method is faster to check if exist or not and then update it with updatestatus function which has memory engine ... or just create some timestamp cloumn in my users table and update it on each page check that have myisam engine??
What you are trying to do, i.e. use two separate engines on the same table does not sound possible. A single engine controls a single table as the most basic level of MySQL. It might be possible to get around that, but it would not be wise. You could edit the source, but that would be crazy. If you are worried about performance, then you could either split your table into multiple tables to use the engines you need on the table you need. Otherwise you could use a caching framework like mem cache (which I recommend) that would boost performance via caching however you need it. Mem cache is a well tested PHP tool and it sounds like what you need. Good Luck.
I have two tables called clients, they are exactly the same but within two different db's. Now the master always needs to update with the secondary one. And all data should always be the same, the script runs once per day. What would be the best to accomplish this.
I had the following solution but I think maybe theres a better way to do this
$sql = "SELECT * FROM client";
$res = mysql_query($conn,$sql);
while($row = mysql_fetch_object($res)){
$sql = "SELECT count(*) FROM clients WHERE id={$row->id}";
$res1 = mysql_query($connSecond,$sql);
if(mysql_num_rows($res1) > 0){
//Update second table
}else{
//Insert into second table
}
}
and then I need a solution to delete all old data in second table thats not in master.
Any advise help would be appreaciated
This is by no means an answer to your php code, but you should take a look # Mysql Triggers, you should be able to create triggers (on updates / inserts / deletes) and have a trigger (like a stored proceedure) update your table.
Going off the description you give, I would create a trigger that would check for changes to the 2ndary table, then write that change to the primary table, and delete that initial entry (if so required) form the 2ndary table.
Triggers are run per conditions that you define.
Hopefully this gives you insight into 'another' way of doing this task.
More references on triggers for mysql:
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
http://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx
You can use mysql INSERT ... SELECT like this (but first truncate the target table):
TRUNCATE TABLE database2.client;
INSERT INTO database2.client SELECT * FROM database1.client;
It will be way faster than doing it by PHP.
And to your notice:
As long as the mysql user has been given the right permissions to all databases and tables where data is pulled from or pushed to, this will work. Though the mysql_select_db function selects one database, the mysql statement may reference another if you use complete reference like databasename.tablename
Not exactly answering your question, but how about just using 1 table, instead of 2? You could use a fedarated table to access the other (if it's on a different mysql instance) or reference the table directly (like shamittomar's suggestion)
If both are on the same MySQL instance, you could easily use a view:
CREATE VIEW database2.client SELECT * FROM database1.client;
And that's it! No synchronizing, no cron jobs, no voodoo :)
I have a classifieds website.
I am using SOLR for indexing and storing data. Then I also have a MySQL db with some more information about the classified which I dont store or index.
Now, I have a pretty normalized db with 4 tables.
Whenever ads are searched on the website, SOLR does the searching and returns an array of ID_numbers which will then be used to query mysql.
So solr returns id:s, which are then used to get all ads from the mysql db with THOSE id:s.
Now, all the JOIN and relations between my tables gives me a headache.
What except for maintanance-ease do I get for having a normalized db?
I could you know, store all info into one table with some 50 columns.
So instead of this for finding one ad and displaying it:
SELECT
category_option.option_name,
option_values.value
FROM classified, category_option, option_values
WHERE classified.classified_id=?id
AND classified.cat_id=category_options.cat_id
AND option_values.option_id=category_options.option_id
I could use this:
SELECT * FROM table_name WHERE classified_id = $classified_id
Isn't the last one actually faster?
Or does a normalized db permform faster?
Thanks
I would advise against denormalizing in your situation. You'll get better with joins as you use them more and they start to become clearer in your head, and maintenance ease is a good benefit for the future.
Here's a pretty good link about normalization (and denormalization). Here's a question about denormalization. One answer suggests creating a view using joins to get the data you need, and using that like your SELECT * FROM table_name WHERE classified_id = $classified_id query. A normalized DB will likely be slower, but it's unlikely you'll want to denormalize for that reason. I hope this provides some help.
Whenever you do denormalization you usually gain reading speed and lose write speed, because you have to write the same value many times. Additionally, extra care should be taken to maintain data integrity.
How many times the query will be executed?
Is this a high traffic application?
Can you add a cache?
The query using a JOIN is trivial as far as MySQL joins are concerned. I see no need to denormalize this.
I would however suggest rewriting it to not be such a PITA to read:
SELECT
category_option.option_name,
option_values.value
FROM classified
JOIN category_option USING (cat_id)
JOIN option_values USING (option_id)
WHERE classified.classified_id = ?
I have a question related to a web app that I developed in PHP, MYSQL.
basically part 1 is :
I display results in the form of table say for software testing.
ID Prod_Name Set Date Result Platform
1 Alpha1 Pro1 01.01.01 PASS 2.3.1.2_OS
Now, I have divided the tables accordingly
Table Name: Results
ID, Name, Date, Result
Table Name : Set
ID, Set_Name, Prod_name
Table Name : Platform
ID, Platform_Name, Set_Name
Now, ID in each table is an incremented value and does not relate to anything else.
My php app, starts with fetching the results from 'Results' table. Since I want SET to be displayed for every row, I am making an another connection to the database and using the query
select Set_name
from Set
where Prod_name = row['Name'] // row['Name'] is fetched from the results table.
now I also want to display platform which I am extracting it from Platform table using the above method i.e making another connection and passing Set_Name = row['Set_Name'] from the Set table.
Now for my application is there any other way to achieve the same result ?
Typically, for large web based applications, if data is coming from a database server is making multiple connection to a DB server a feasible option?
Please do not consider the fact that with MySQL declaring a connection statement once will do the needful but what about MSSQL server? Do we need to write a long sql statement with several joins/selfjoins/unions and use those variables all over the application?
How is the application design for this case will be?
Can anyonce give me some ideas please?
Thanks.
For pretty much any flavour of database, a single SELECT statement which joins three tables will perform better than three separate statements querying a table apiece. Joining is what relational databases do.
I may not have understood everything, but here is something similar. First, let's make an ER model.
Now, because you don't seem to like joins, create a view in the database.
CREATE VIEW v_test AS
SELECT TestID, ProductName, TestName, Date, Result, PlatformName
FROM Product AS p
JOIN Test AS t ON t.ProductID = p.ProductID
JOIN Platform AS f ON f.PlatformID = t.PlatformID;
With this in place, you can simply use:
SELECT * FROM v_test WHERE ProductName = 'Alpha1'
You may also take a look at this question/answer with a similar scenario.