Using SELECT result as a column name in WHERE clause - mysql

What would be the fastest way to delete all records in every table of the database with id = 0?
It would be simple if every table had its first column called id, but in my case one table has first column named id_tag, other table - id_product, etc.
I've figured out that I can get the name of the first column by:
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME = 'ps_tag' LIMIT 1
but how can I include it in a DELETE query? I need something like:
DELETE FROM 'ps_tag' WHERE [first_column] = 0
My first idea was:
DELETE FROM 'ps_tag'
WHERE (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'dbname' AND TABLE_NAME = 'ps_tag' LIMIT 1) = 0
but obviously it doesn't work.

Although you can set up a dynamic SQL statement, I often find this type of operation is easier to do in Excel. Write a query to get the column name and table name for the ones you are interested in.
Then, load these into Excel.
In another cell, put in a string like 'delete from #table where #column = 1'.
Then put in the formula:
=substitute(substitute(<where the string is>, '#table', <tablename>), '#column', <columnname>))
Copy the code back to your database interface and execute it.
(And any spreadsheet will do. I usually have Excel handy.)

Related

Getting all data from result of search in MYSQL sql

Hi everyone I have multiples tables which I want to get tables with specific column name which I am able with the following code:
SELECT COLUMN_NAME AS 'ColumnName'
,TABLE_NAME AS 'TableName'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'DATABASENAME'
AND COLUMN_NAME LIKE '%columnName_I_Need%' // Example not actual search
ORDER BY TableName
,ColumnName;
Now I want to get the all data from the resulted tables.
For example, get all columns and their data in resulted tables.
This is an example but is not working :
SELECT * WHERE columnName_I_Need = 1
Is this possible with MySQL?
MySQL version: 5.5.5-10.3.23 MariaDB
This is quite complicated. If you used only dynamic SQL, you would need a looping mechanism. My recommendation is to generate the SQL and then run it manually:
SELECT GROUP_CONCAT('SELECT * FROM ', TABLE_NAME,
' WHERE ', COLUMN_NAME, ' = 1'
SEPARATOR ';
'
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'DATABASENAME' AND
COLUMN_NAME LIKE '%columnName_I_Need%';
Then copy the statement and run it manually.
The 'FROM' is missing in your query. Also when you specify a column name it should be written inside single quotes.
SELECT * FROM your_table_name WHERE columnName_you_Need = 'colum_id'
This is a simple and basic query to access the data from the table.
SELECT * FROM tablename
WHERE can include a condition here.
* is used to select each and every column.
One can use the column name to access a particular column.

Knowing if a specific column exists or not

Hi, when entering the following url (for learning purpose only) I can see an image with id=1.
So I tried this to find the names of some tables inside the database, and it worked. This can detect if a table starting with 'albu' exists or not:
http://35.227.24.107:5001/d0510b3060/fetch?id=1 AND (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'albu%')>0; --
But how could I know if a specific column that its name starts with 'albu' exists or not? I already tried this, but it didn't work:
http://35.227.24.107:5001/d0510b3060/fetch?id=1 AND (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'albums' AND column_name LIKE 'albu%')>0; --
Please Note: for my question, I know both the name of the db and the table.
As commented by Shadow, you are looking for MySQL INFORMATION_SCHEMA.COLUMNS table :
SELECT COUNT(*)
FROM information_schema.columns
WHERE table_name = 'albums' AND column_name LIKE 'albu%'
NB : you might also want to filter on the TABLE_SCHEMA. It takes the schema and the table name to uniquely identify a table in the database.

How do I find a table in MySQL with 2 specific columns in it

Similar to How to find all the tables in MySQL with specific column names in them? I would like to find the table with 2 specific columns, not either or.
I've tried combining with AND but no dice.
For instance, I want to search the database for the specific tables that contain both CategoryID and LotNumber columns.
Through the information_schema.columns table, grouping the matching columns by table and returning only those with number equal to 2:
SELECT table_name
FROM information_schema.columns
WHERE (column_name = 'colname1' OR column_name = 'colname2')
[AND table_schema = 'dbname']
GROUP BY table_name
HAVING count(*) = 2;
You can try something like :
SELECT * from TableName where obj1 = "obj1" and obj2= "obj2"
this is an example.
Let me know how it worked :)

MySQL INTO OUTFILE Query problems

I have written this simple query which would pull out all the data from table into a CSV file.
SELECT Group_concat(Concat(column_name))
FROM information_schema.columns
WHERE table_name = 'subject_assignment'
AND table_schema = 'newschema2'
UNION ALL
SELECT (SELECT Group_concat('`', column_name, '`')
FROM information_schema.columns
WHERE table_name = 'subject_assignment'
AND table_schema = 'newschema2')
FROM subject_assignment
INTO OUTFILE 'D:\\export\\asd.csv'
Now, the first bit works great but I have issues with the second part.
Instead of pulling out data from columns specified in column list it just displays me all the column names over and over again.
Could you please suggest what I am doing wrong?
Thanks.
In your second SELECT you do not select any column from subject_assignment. Instead, you're selecting single string value made from concatenated column names. And you're selecting it as many times as the row count of subject_assignment.
UPDATE:
If you want to dynamically create column names and then select data from them, see this: https://stackoverflow.com/a/17573774/925196

Query a database with results from multiple tables?

There are some similar questions around but they aren't quite what I'm looking for, so forgive me if you think this is answered elsewhere.
I am basically looking for an easy way to do things as I have over 4000 tables to get data from. This kind of follows on from my previous post: mysql search for segment of table name
The general situation is that I have a database filled with tables and I only want about a quarter of this which comes to around 4000 tables. I have a list of the individual table names thanks to my previous post, but I want the data that goes with them.
I know that for an individual one I can do SELECT table1.*, table2.*; or something similar but I don't want to go through all 4000 or so.
They all end with the same thing, e.g. staff_name, manager_name, customer_name so I can use
SHOW TABLES LIKE '%_name'
to see the table names that I want in the database. Someone suggested using dynamic mysql, but I don't even know where to start with that. Any suggestions?
Generic example (in PHP):
Constructing dynamic SQL or building your SQL queries with the aid of a programming language would look like this (in PHP for ex.):
$pdos = $pdo->query("SHOW TABLES LIKE '%_name'");
$tables = $pdos->fetchAll();
$query = 'SELECT * FROM '.implode(' UNION SELECT * FROM ');
$pdo->query($query);
The fetchAll method will return an array containing the names of each table selected.
The implode($glue, $array) function takes an array and concatenates every value in the array using the $glue parameter - usually you take an array of values and implode them using $glue = ',' to create a coma separated list of values.
In our case the implode has a partial query as $glue in order to create one big UNION JOIN query.
Once the final $query is build it should look something like:
SELECT * FROM table_1_name
UNION
SELECT * FROM table_2_name
UNION
SELECT * FROM table_3_name
....
....
UNION
SELECT * FROM table_4000_name
The result should contain all of the DISTINCT rows from all 4000 tables.
Specific example (in SQL-only format):
SELECT GROUP_CONCAT(
CONCAT('select * from ', table_name)
SEPARATOR ' union '
)
INTO #my_variable
FROM information_schema.tables
WHERE table_schema = 'dbname'
AND table_name LIKE '%_name';
PREPARE my_statement FROM #my_variable;
EXECUTE my_statement;
The first statement will get all of the table names from the information_schema database;
The CONCAT function prefixes every table name with a a 'SELECT * FROM ' string;
The GROUP_CONCAT does the job that implode would have done in PHP;
The INTO clause makes sure the values are saved inside a variable named my_variable;
The PREPARE statement takes a string value (such as the one you saved in my_variable) and checks if the value is an SQL query;
The EXECUTE statement takes a "prepared statement" and well... executes it.
#my_variable is a temporary variable but it can only be of a scalar type (varchar, int, date, datetime, binary, float, double etc.) it is not an array.
The GROUP_CONCAT function is an "aggregate function" which means it takes an aggregate value (similar concept to an array - in our case the result set of our query) and outputs a simple string result.
I would suggest generating the SQL statement.
Try doing:
select concat('select * from ', table_name) as query
from Information_Schema.tables
where table_schema = <dbname> and
table_name like <whatever>
You can then run this as a bunch of queries by copying into a query editor window.
If you want everything as one query, then do:
select concat('select * from ', table_name, ' union all ') as query
from Information_Schema.tables
where table_schema = <dbname> and
table_name like <whatever>
And remove the final "union all".
This has the table name matching a like. Leave out the table_name part of the WHERE to get all tables. Or, include specific tables using table_name in ().