How to select all the tables from multiple databases in mySql..
I am doing the following steps but not able to achive the goal.
<?php
$a = "SHOW DATABASES";
$da = $wpdb->get_results($a);
foreach($da as $k){
echo '<pre>';
print_r ($k->Database);//prints all the available databases
echo '</pre>';
$nq = "USE $k->Database";//trying to select the individual database
$newda = $wpdb->get_results($nq);
$alld = "SELECT * FROM $k->Database";
$td = $wpdb->get_results($alld);
var_dump($td);//returns empty array
}
?>
Please Help me
Use the INFORMATION_SCHEMA:
select table_schema, table_name from information_schema.tables;
Even better:
Show all tables in all databases (except internal mysql databases) in one SQL statement.
SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema NOT IN ( 'information_schema', 'performance_schema', 'mysql' )
You cannot do
SELECT * FROM database
but you can do
USE DATEBASE;
SHOW TABLES;
or even better:
SHOW TABLES IN database
I would go for this this:
mysql -e "select table_schema, table_name from information_schema.tables;" | \
grep -Pv '^(sys|performance_schema|TABLE_SCHEMA|mysql|information_schema)' | \
perl -pe 's/\s+/./' | \
sort -u
mysql -e'select table_schema, table_name from information_schema.tables;'
This depends on you having a file ~/.my.cnf in place with the following contents:
[client]
user=ADMINUSER ## set user, usually 'root'
password=PASSWORD ## set password
Related
How to export some rows of a MySQL table with where clause from a PHP script?
I have a MySQL say test and I want to create a importable .sql file for rows where id are between 10 and 100, using PHP script.
I want to create a sql file say test.sql which can be imported to MySQL database.
Mycode:
$con=mysqli_connect("localhost", "root","","mydatabase");
$tableName = 'test';
$backupFile = '/opt/lampp/htdocs/practices/phpTest/test.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName WHERE id BETWEEN 10 AND 500";
$result = mysqli_query($con,$query);
This creates a test.sql file, but when I try to import, it gives error #1064.
My script only creates a file with rows with columns name and table sturcute or insert query.
As mentioned in the comments you can use mysqldump the following way.
mysqldump --user=... --password=... --host=... DB_NAME --where=<YOUR CLAUSE> > /path/to/output/file.sql
If you want this to be in your php file you can do the following
exec('mysqldump --user=... --password=... --host=... DB_NAME --where=<YOUR CLAUSE> > /path/to/output/file.sql');
In very simply way go to your phpMyAdmin
select you database whose particular rows you want to export
click on "SQL" (To Run SQL query/queries on database)
Write sql query and execute it
Like select * from test table limit 500 now what ever result come
Just at the bottom see "Query results operations"
just click on Export
All done :-)
Mysql Shell command
mysqldump -u user -p password -h host Database Table --where="Condition"> /path/exportFile.sql
Example
mysqldump -u user -p 123456 -h host Database Student --where="age > 10"> /path/exportFile.sql
If you have exported data using OUTFILE then you have to import it using INFILE COMMAND
$con=mysqli_connect("localhost", "root","","mydatabase");
$tableName = 'test';
$backupFile = '/opt/lampp/htdocs/practices/phpTest/test.sql';
$query = "LOAD DATA INFILE '$backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
OR you can make csv file using
$con=mysqli_connect("localhost", "root","","mydatabase");
$tableName = 'test';
$backupFile = '/opt/lampp/htdocs/practices/phpTest/test.sql';
$query = 'SELECT * INTO OUTFILE '."'$backupFile'".'
FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '.'\'"\'
LINES TERMINATED BY \'\n\'
FROM '.$tableName.' WHERE id BETWEEN 10 AND 500';
$result = mysqli_query($con,$query);
and then import this file.
Hope this works...
I want to make specific .sql file for each of my routines.
#!/bin/bash
routine_names=$(mysql mydb --execute="SELECT
*
FROM
information_schema.routines
WHERE
routine_type = 'PROCEDURE' OR routine_type ='FUNCTION'
AND routine_schema = 'mydb';"|cut -f1)
for routine in "$routine_names"
do
if [ -e "${routine}.sql" ]
then
echo "ok"
else
content_procedure=$(mysql mydb--execute="SHOW CREATE PROCEDURE $routine;")
echo "$content_procedure" >> masoud.txt
fi
done
my routine_names variable is a list of my procedures. like this:
SP_ONE
SP_TWO
SP_THREE
I want to loop of these result. but I think the result is not an array. because routine variable has all content.
wrap your mysql mydb ... command with ()
routine_names=($(mysql mydb --execute="SELECT
*
FROM
information_schema.routines
WHERE
routine_type = 'PROCEDURE' OR routine_type ='FUNCTION'
AND routine_schema = 'mydb';"|cut -f1))
I was curious and got the idea from here.
Just another case how I fix my problem
#!/bin/bash
mysql -u USER -p -h localhost -D database1 -e "SELECT ID FROM prodTable WHERE display=1 AND new=1 AND exDate<DATE_SUB(CURDATE(),INTERVAL 2 YEAR)" | while read ID;
do
echo "The following product has been moved: $ID"
done
I have migrated a MySQL database to PostgreSQL & replaced the querySHOW FULL COLUMNS FROM schema_name.table_name; with a Postgres equivalent,
SELECT * FROM information_schema.columns WHERE table_schema = 'schema_name' and table_name = 'table_name'; which returns the columns along with their properties however the 'Comment' property that was returned in the MySQL query is not returned in the PostgreSQL query.
Is there a way to query for the comments associated with each column_name?
How about this:
select col_description((table_schema||'.'||table_name)::regclass::oid, ordinal_position) as column_comment
, * from information_schema.columns
WHERE table_schema = 'schema_name'
and table_name = 'table_name';
You know this is shown under \dt+ you can reverse engineer what psql does with -E
-E --echo-hidden Echo the actual queries generated by \d and other backslash commands. You can use this to study psql's internal operations. This is equivalent to setting the variable ECHO_HIDDEN to on.
psql -d test -E -c'\dt+ foo'
********* QUERY **********
SELECT n.nspname as "Schema",
c.relname as "Name",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner",
pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as "Size",
pg_catalog.obj_description(c.oid, 'pg_class') as "Description"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','s','')
AND n.nspname !~ '^pg_toast'
AND c.relname ~ '^(foo)$'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;
**************************
You can see here all the information that psql shows. As they say, teach the man to fish... ?
I have a simple bash script. I wish to get an exact count of the number of rows in each table of the database.
#!/bin/bash
TABLES_OLD=$( mysql -u user -ppassword MySchema --batch --skip-column-names -e"SHOW TABLES FROM MySchema" )
for table in "${TABLES_OLD[#]}"
do
QUERY="SELECT COUNT(*) FROM ${table}"
echo "${QUERY}"
done
The script prints:
SELECT COUNT(*) FROM Table 1
Table2
Table3
Table4
etc...
Clearly this is not what I want, and I don't even understand how what is happening is possible. What am I doing wrong?
Try this, put the tables into an array then loop thru the results
db_host='host'
db_user='user'
db_pass='password'
db='your_db'
read -ra var_id <<< $(mysql -h $db_host -u $db_user -p$db_pass $db -sse "show tables from $db")
for i in "${var_id[#]}";
do
results=$(mysql -h $db_host -u $db_user -p$db_pass $db -sse "select count(*)from $i")
echo "$i $results"
done
This should do it :
#/bin/bash
mysql -u user-ppassword -e "SELECT table_name, table_rows
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'your_data_base_name';"
Replace echo with eval
The code will be
#!/bin/bash
TABLES_OLD=$( mysql -u user -ppassword MySchema --batch --skip-column-names -e"SHOW TABLES FROM MySchema" )
for table in "${TABLES_OLD[#]}"
do
QUERY="SELECT COUNT(*) FROM ${table}"
eval "${QUERY}"
done
I've been working on this script for a couple of days now (i'm recently started writing in bash)
The script checks when a column is near to reach its auto_incement limit. I could of just get the auto_increment value from information schema. But, because we have hundreds of tables and about 4TB of data that would of taken awhile. So I decided to get the auto_increment value from 'SHOW CREATE TABLE' which hopefully will be faster(still have to run this in staging). I'm sure there are multiple ways to solve this problem and like I said I'm not an bash script expert but I would like your opinion and If there is anything I could be doing better. Hopefully this also helps others.
Thank you! -Gio
#!/bin/bash
#
# This is bash script checks when auto_increment column is reaching its limit
# To run Script $ ./auto_increment_check.sh [username] [password] [host]
MYSQL_USER="$1"
MYSQL_PASSWD="$2"
MYSQL_HOST="$3"
MYSQL=$(which mysql)
if [ $? != 0 ]
then
echo -e "\nMYSQL CLIENT NOT PRESENT!\n"
exit 1
fi
MYSQLCONNECT="$MYSQL -u$MYSQL_USER -p$MYSQL_PASSWD -h $MYSQL_HOST"
QUERY="
SELECT table_schema,
table_name,
data_type,
( CASE data_type
WHEN 'tinyint' THEN 255
WHEN 'smallint' THEN 65535
WHEN 'mediumint' THEN 16777215
WHEN 'int' THEN 4294967295
WHEN 'bigint' THEN 18446744073709551615
end >> IF(Locate('unsigned', column_type) > 0, 0, 1) ) AS MAX_VALUE
FROM information_schema.columns
INNER JOIN information_schema.tables USING (table_schema, table_name)
WHERE table_schema NOT IN ( 'MYSQL', 'INFORMATION_SCHEMA', 'PERFORMANCE_SCHEMA'
)
AND extra = 'auto_increment'"
$MYSQLCONNECT --batch -N -e "$QUERY" | while read DATABASE TABLE DATA_TYPE MAX_VALUE;
do
NEXT_AUTO_INCREMENT=`mysql -uroot -pgio --batch -N -e "SHOW CREATE TABLE $DATABASE.$TABLE" | awk -F'AUTO_INCREMENT=' 'NF==1{print "0";next}{sub(/ .*/,"",$2);print $2}'`
AUTO_INCREMENT_RATIO=$(awk 'BEGIN {printf "%2.2f\n", '$NEXT_AUTO_INCREMENT' / '$MAX_VALUE'}')
[[ $(awk 'BEGIN{print ('$AUTO_INCREMENT_RATIO'>=0.9)}') -eq 1 ]] && echo "Auto Increment limit almost reached! $DATABASE.$TABLE - NEXT_AUTO_INCREMENT= $NEXT_AUTO_INCREMENT, MAX= $MAX_VALUE, RATIO= $AUTO_INCREMENT_RATIO"
done
If information_schema is slow for you, I recommend setting innodb_stats_on_metadata=0.
As for monitoring auto increment capacity, you should do this with common_schema.
Once common_schema is installed you can run a query like this:
select *
from common_schema.auto_increment_columns
order by auto_increment_ratio desc
limit 10;
For further information please read the blog post I wrote on this subject last year.