I have a small PHP Mysql function which generates all the columns within a mysql table, but I would like the function not to display the primary keys for each table just the other columns.
How can this be done, I havent been able to find the code for it.
Thanks
It seems I didnt explain the question well.
The mysql table from which the columns are generated is sent on demand from a list of ALL THE TABLE IN THE DB (over 150) and I cant specify the exact columns for each of the table.
It would just be more efficient if I found a way of omitting the primary key from the result.
Since it isnt required for the subsequent processing and quite confusing to the enduser as to its use.
Thanks
Use:
SELECT column1, column2, column3 FROM table
For what it's worth, returning the PK or not isn't going to break the bank.
In general, doing SELECT * FROM is bad, but if you're just going to do SELECT every, column, but, the, pk FROM then you may as well just select everything.
The best answer is just to SELECT the columns you need. If you need 3 columns, query for 3 columns and name them explicitly: SELECT column1, column2, column3 FROM table_name
Related
I have 2 tables with similar columns in MYSQL. I am copying data from one to another with INSERT INTO table2 SELECT * FROM table1 WHERE column1=smth. I have different columns as autoincrement and KEY in tables. When I use mysqli_insert_id i get the first one rather then last one inserted. Is there any way to get the last one?
Thanks
There is no inherit ordering of data in a relational database. You have to specify which field it is that you wish to order by like:
INSERT INTO table2
SELECT *
FROM table1
WHERE column1=smth
ORDER BY <field to sort by here>
LIMIT 1;
Relying on the order a record is written to a table is a very bad idea. If you have an auto-numbered id on table1 then just use ORDER BY id DESC LIMIT 1 to sort the result set by ID in descending order and pick the last one.
Updated to address OP's question about mysqli_insert_id
According to the Mysql reference the function called here is last_insert_id() where it states:
Important If you insert multiple rows using a single INSERT statement,
LAST_INSERT_ID() returns the value generated for the first inserted
row only. The reason for this is to make it possible to reproduce
easily the same INSERT statement against some other server.
Unfortunately, you'll have to do a second query to get the true "Last inserted id". Your best bet might be to run a SELECT COUNT(*) FROM table1 WHERE column1=smth; and then use that count(*) return to add to the mysqli_insert_id value. That's not great, but if you have high volume where this one function is getting hit a lot, this is probably the safest route.
The less safe route would be SELECT max(id) FROM table2 or SELECT max(id) FROM table2 Where column1=smth. But... again, depending on your keys and the number of times this insert is getting hit, this might be risky.
I have a SQL table with two columns:
'id' int Auto_Increment
instancename varchar
The current 114 rows are ordered alphabetically after instancename.
Now i want to insert a new row that fits into the order.
So say it starts with a 'B', it would be at around id 14 and therefore had to 'push down' all of the rows after id 14. How do i do this?
An SQL table is not inherently ordered! (It is just a set.) You would simply add the new row and view it using something like:
select instancename
from thetable
order by instancename;
I think you're going about this the wrong way. IDs shouldn't be changed. If you have tables that reference these IDs as foreign keys then the DBMS wouldn't let you change them, anyway.
Instead, if you need results from a specific query to be ordered alphabetically, tell SQL to order it for you:
SELECT * FROM table ORDER BY instancename
As an aside, sometimes you want something that can seemingly be a key (read- needs to be unique for each row) but does have to change from time to time (such as something like a SKU in a product table). This should not be the primary key for the same reason (there are undoubtedly other tables that may refer to these entries, each of which would also need to be updated).
Keeping this information distinct will help keep you and everyone else working on the project from going insane.
Try using an over and joining to self.
Update thetable
Set ID = r.ID
From thetable c Join
( Select instancename, Row_Number() Over(Order By instancename) As ID
From CollectionStatus) r On c.instancename= r.instancename
This should update the id column to the ordered number. You may have to disable it's identity first.
I have 2 tables. suppose a & b
a has id, name, roll. b has id,group,name
This name column data are not same. How can I select and uniquely identify them?
I know about
SELECT a.id,a.name,a.group FROM a,b ............
I know this. But this is an example. I am working with huge amount of data with 20-30 columns in each table. So I don't want to write the column names I need to select rather I want to write the names that I want to exclude.
Like
SELECT * Except b.name............
OR is there any way to uniquely identify after join. Like
.......... a,b WHERE a.name as name1
Please don't ask why those column names are same. I admit it was a mistake. But it's already implemented and heavily used. So finding another way. Is there any simple way to exclude a column while merging them?
Well, you can't write the names you wish to exclude. That is not how SQL works.
However, if writing out 20-30 column names is that much of a burden, you can use information_schema.columns. I write it that way, because 20-30 column names is not particularly large and writing them out is probably less effort than writing the question.
But, back to the solution. It looks something like this:
select concat(c.column_name, ' as ', 'a_', column_name, ', ')
from information_schema.columns c
where table_name = 'a' ;
You might want to include the table schema as well.
As an IDEA, what you can do is, if you want to avoid columns of specific table & your statements have multiple table, you can try following,
Suppose you have 20 columns in table a & 5 columns in table b, you want to avoid col2,col3 & col4 of table b. Standard method is that you should write name of all columns of table a & required columns of table b. But you can avoid to write long list of 20 columns of table by writing a.* & then type required columns of table b. Please see below statement.
Select a.*,b.col1,b.col4,b.col5 from a,b
But if you require to exclude some columns from both table, then I think there is no other way than writing all required column names from both table.
There is no way to exclude a column in SQL SELECT Statement, you can only select a column. You can give alias name to columns while selecting them like below, so that you can identity columns using those alias names.
SELECT a.id as [column1],a.name as [column2],a.group as [column3] FROM a,b ............
There is no way to exclude a specific column but you can avoid to write all columns name and easy your job by below steps-
Step1: Execute below query-
SELECT a.*,b.* FROM a,b ............limit 1;
Step2: Export it into csv format with headings.
Step3: Copyp first (heading) row from csv.
Step4: Delete columns, those are not required and use other columns in your query.
There's only one waY i could see-
first create a temorary table
CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
then put your column in temporary table-
SELECT * INTO mytable
FROM YourTable
/* Drop the cloumns that are not needed */
ALTER TABLE mytable
DROP COLUMN ColumnToDrop
/* Get results and drop temp table */
SELECT * FROM #TempTable
DROP TABLE #TempTable
I have a table called scheduler_sched which has several columns, including a column called schedule_id.
I need a function where I can pass 2 ids (copy_from_id, copy_to_id) as parameters. And what I need to do is take every row where schedule_id = copy_from_id AND duplicate it but change the copy_from_id to the copy_to_id
So basically I want to to the equivalient of this:
UPDATE scheduler_sched SET schedule_id = 32 WHERE schedule_id = 28
Only I do not want to UPDATE any rows, I want to create duplicates with the new ID's
Does this make sense?
How can I do this?
THANKS!
(By the way schedule_id is not a unique/index field on this table)
Insert into scheduler_sched (column1, column2, column3,schedule_id )
Select column1, column2, column3, 32 from scheduler_sched WHERE schedule_id = 28
I think that ON DUPLICATE KEY UPDATE syntax may help you:
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
e.g.:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
Just INSERT a new row instead of updating. SELECT first if that schedule_id 28 exists, and if it does, insert a new one with that being the ID.
Since you haven't specified a version of MySQL, I'm going to assume that it is the lastest (5.4).
Assuming I am understanding you correctly, you should be able to implement this using triggers: http://dev.mysql.com/doc/refman/5.4/en/create-trigger.html
One of the benefits of using triggers, is it is all handled by the database itself.
I have three tables, each contain an auto-incrementing PK. I need to select the latest (ie, ORDERBY DESC) entries from the mix of these tables.
I'd like to do it in one query, with two joins.
My idea was is to somehow select a table, order it by id DESC, then somehow merge the results.
Does anyone have a way (or probably a better idea) of doing this?
(using mysql)
EDIT:
Sorry - here's a more detailed spec:
I have three tables, posts, stories, favs.
Each has (at the least) three columns id, uid and date. They are both PK's. id auto-increments (separately for each table). uid is FK, but that's irrelevant. I need the result set to contain the latest 20 or 30 entries.
UNION with no joins would be a possability.
see http://dev.mysql.com/doc/refman/5.0/en/union.html for details.
Since the tables have no relation, joining them doesn't make any sense, right?
As far as I understood, You would like to order records originating from 3 different tables in one result set by their creation date. There are two ways to achieve this:
Use a PK that is sortable and unique for all 3 tables. I know You can do this easily in PostgreSQL. In MySQL You need a workaround: Create a 4th table with an auto-increment PK and change the other 3 tables PK to a FK pointing at the 4th table PK. This is somewhat cumbersome and You need to be aware of the fact, that an auto-increment field is not a good candidate for a reliably sortable property (deleting records leads to gaps in the sequence, which might be filled later).
Add a column created to each of the 3 tables and store the creation date of each record. The UNION can then be sorted by this column. You already have a column date. Can't You use this column?