How do I create a table name in MySQL using a select? - mysql

I'm building a MySQL event to make a copy of a table in the database with a timestamp in the name.
CREATE TABLE `db_name`.`tbl_prefix_(SELECT TO_SECONDS(NOW()))` ( [the rest...]
Obviously this isn't working. What should I do to make it work?
Any suggestions are welcome.
Thanks

This is a bad architecture. Generating tables on the fly is not something you should do.
Instead, create a single table with a timestamp column. For instance, if you would before have 3 tables with three timestamps A, B, and C, you now have one table with a timestamp column containing the values A, B, and C, respectively.

In order to do this, you would need to use "dynamic SQL". That is, make use of the MySQL PREPARE statement.
What you'd need to do is populate a variable with a string that contains the SQL text you want to execute. Doing variable substitution into string is trivial.
The "trick" is to take that dynamic string and execute it like it was a SQL statement.
And that's what the PREPARE statement does for us, takes in a variable, and reads the contents of that variable like it were a SQL statement.
With that said, rather than give an example code that demonstrates this in more detail, I'm going to suggest that you re-think this idea of creating a table with timestamp value as part of the name.
What problem is that designed to solve? And carefully consider whether the proposed design for a solution will introduce a bigger problem than it solves.

Related

SQL: Extract column headings from Dynamically Generated Table

After selecting data from multiple tables, like this:
SELECT games.name, scores.score
FROM games, scores
WHERE players.id = scores.player_id
..can I extract the column headings of this newly generated table?
The statement I'd normally use would be as follows:
SELECT column_name
FROM information_schema.columns
WHERE table_name=table
But naturally this would not work for a dynamically generated table with no name
Help much appreciated!
Edit: I'm using the MariaDB client
..can I extract the column headings of this newly generated table?
No. Mostly because you've not created a table. Just a result set. I think you already know this, because you've already looked at the information schema :)
Unfortunately it seems even creating a temporary table won't help - because those aren't stored in the information schema either. I don't think you can declare cursors for SHOW COLUMN... statements either.
I don't think you've got a way to do it I'm afraid.
If it's a prepared statement (with the select statement held in a variable) you could probably chop it up using some ugly string manipulation...?
It might at this point be worth asking "more abstractly, what problem are you trying to solve?"

MySql - Select * from 2 tables, but Prefix Table Names in the Resultset?

I'd like to select * from 2 tables, but have each table's column name be prefixed with a string, to avoid duplicate column name collissions.
For example, I'd like to have a view like so:
CREATE VIEW view_user_info as (
SELECT
u.*,
ux.*
FROM
user u,
user_ex ux
);
where the results all had each column prefixed with the name of the table:
e.g.
user_ID
user_EMAIL
user_ex_ID
user_ex_TITLE
user_ex_SIN
etc.
I've put a sql fiddle here that has the concept, but not the correct syntax of course (if it's even possible).
I'm using MySql, but would welcome generic solutions if they exist!
EDIT: I am aware that I could alias each of the fields, as mentioned in one of the comments. That's what I'm currently doing, but I find at the start of a project I keep having to sync up my tables and views as they change. I like the views to have everything in them from each table, and then I manually select out what I need. Kind of a lazy approach, but this would allow me to iterate quicker, and only optimize when it's needed.
I find at the start of a project I keep having to sync up my tables and views as they change.
Since the thing you're trying to do is not really supported by standard SQL, and you keep modifying database structures in development, I wonder if your best approach would be to write a little script that recreates that SELECT statement for you. Maybe wrap it in a method call in the development language of your choice?
Essentially you'd need to query INFORMATION_SCHEMA for the tables and columns of interest, probably via a join, and write the results out in SQL style.
Then just run the script every time you make database structural changes that are important to you, and watch your code magically keep up.

MySQL: eliminating functions from queries

How can I write this mysql query without using functions?
SELECT word
FROM dvddict
JOIN dvdrevdict
ON word=RIGHT(revword, 4)
WHERE LENGTH(revword)=9;
The dvddict table has a column word and the dvdrevdict table has a column revword, which is just the reverse of the word column. I want to write it without having to use both RIGHT() and LENGTH() functions.
Thanks!!
Add two columns revword_right and revword_length to dvdrevdict, then have a trigger populate them on insert or update.
Unfortunately MySQL has no function based indexes which could probably help you (in the where length.. case) as well if your goal is to speed things up.

Create columns that autoincrement with name in a MySQL Database

I know that this might seem like a strange question, but let me try and explain it. I have a database table called 'plan' and in it the first column is called 'username' and the columns after it are called 'question1', 'question2' and so on. I now need to add a hundred or so more columns named like this, but it would be nice to have a sql statement that would automatically do that for me.
I know this wasn't set up in the best way, but if you have a solution, please let me know :)
There isn't any SQL command or feature that would do this automatically; sure you can generate the alter table statements and add the columns programmatically; however, your design would be terribly flawed.
Instead of adding columns, you should create a table containing the question, the user_id (or username, whatever is the PK) to hold the records. If you need to identify a question by number (or ID), simply add another column called question_id.
Write the query in sql to excel. Seperate the incrementing number. Drag down until excel row 100. Hard to explain but i guess you ll figure it out. You'll have 100 incrementing add column sql statements. copy paste run it on a query tool.

Is there any list datatype in MySQL stored procedures, or a way to emulate them?

I would like to create a stored procedure in MySQL that took a list as argument. For example, say that I would like to be able to set multiple tags for an item in one call, then what I want to do is to define a procedure that takes the ID of the item and a list of tags to set. However, I can't seem to find any way to do this, there is no list datatype, as far as I'm aware, but can it be emulated somehow? Could the list of tags be a comma-separated string, which can somehow be split and looped over?
How do you usually work with lists in MySQL stored procedures?
This article has some good discussion on the problem of parsing an array to a stored procedure since stored procedures only allow valid table column data-types as parameters.
There are some neat things you can do with the csv table type in mysql - that is if you are loading a flat file into the db.
You could create a temporary table in the stored procedure, iterate over the csv list and insert it to the temp table, then create a cursor which selects the values from that table. This answer in the above mentioned thread shows a way of doing this.
Generally I would split the array before I come to the database and then perform the query individually on each item.
Depending on how complicated you want to get, you can use a generic linking table. For one of my applications there are several reports where the user might pick, for instance a list of customers to run the report on rather than just a single customer from a combo box. I have a separate table with 2 fields:
UniqueID (guid)
ItemID
The psuedo-code looks like this:
GUID guid = GenerateGUID()
try
for each customer in customerList { INSERT(guid, customerId) }
ExecuteSQLPocedure(guid)
--the procedure can inner-join to the list table to get the list
finally
DELETE WHERE UniqueID=guid
In my programming language of Choice, C#, I actually do this in the application itself because split() functions and loops are easier to program in C# then SQL, However!
Perhaps you should look at SubString_Index() function.
For example, the following would return google:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('www.google.com', '.', -2), '.', 1);
Not sure if these will work specifically in a SP, but there are ENUM and SET datatypes in MySQL 5 which may do what you need.
http://dev.mysql.com/doc/refman/5.0/en/enum.html
http://dev.mysql.com/doc/refman/5.0/en/set.html