Find Row Number of Record in MySQL - mysql

Suppose I have a table with one column - called 'person' that contains a list of names. I want to find a specific person based off his index.
I tried using a sql variable to track each column index but the issue is - is that if I have a table of 5 records this will always output the 5th record.
SET #row_num = 0; SELECT #row_num := #row_num + 1 as row1 ,person FROM table;
SELECT row1 from table WHERE person = 'name'

I would recommend changing your database to add a second column for row_id. This is a fairly common practice. Then you can just use
SELECT * from table WHERE row_id = 3;
This will return the third row.

Another best possible way would be by means of a TEMPORARY TABLE as explained below
create a temp table
create temporary table temptab(ID INT NOT NULL AUTO_INCREMENT,Person VARCHAR(30))
Then insert data to temp table as
insert into temptab(Person) select Person from mytable
Then select the specific index person name from temp table like
select Person from temptab where ID = 5

Related

Fill Column of SQL Table

I'm trying to fill a certain column of a SQL table with data from another table. I have a column named "size" in my table which should return the number of rows in the 2nd table where the id of both rows is the same. Is there a way to populate a SQL column based on a certain command? I would love to be able to fill the column based on this command:
SELECT count(*)
FROM second_table
WHERE id = "row_id";
Here is a sample database with the two tables:
Table 1
Name
id
tiger
1
lion
2
gazelle
1
Here is the desired output for Table 2:
id
Number of Animals
1
2
2
1
I am trying to fill the Number of Animals column but do it automatically and dynamically when another row is added or deleted to Table 1, which is why I want the Select count(*) SQL statement as the code for the column.
One method is a correlated subquery:
update table1 t1
set size = (select count(*)
from table2 t2
where t2.id = t1.id
);
If you need to do this dynamically (as data is inserted), then you would need to use a trigger. However, I would suggest that you calculate the value as needed, unless there is a specific reason why you need to store it.
I guess you need something like this:
CREATE TRIGGER UpdateAnimalCountTable2
AFTER INSERT ON `Table1` FOR EACH ROW
begin
DECLARE NewCount int;
SELECT count(1)
INTO #NewCount
FROM Table1
WHERE Table1.id= NEW.id;
UPDATE Table2
SET NoOfAnimals = #NewCount
WHERE id = NEW.id;
END;
Above is the trigger which will be executed after every insert in Table1 and will update the count in Table 2 for ID which just got inserted in Table1.

Insert from MySQL joined table

I have two databases named drupal and wordpress. I try to migrate post image paths from drupal 6 to wp.
Tables drupal.content_field_image and drupal_files contain necessary data:
drupal.content_field_image has field_image_fid - nid pair. drupal.drupal_files has fid - filepath pair (field_image_fid = fid).
I need to get the table that contains both nid and filepath, so I join this tables:
SELECT *
FROM `content_field_image`
JOIN `files` ON content_field_image.field_image_fid = files.fid;
Now I need to insert data to wordpress db so that:
meta_id = 34 + n (n is increment)
post_id = nid from joined table
meta_key = fifu_image_url
meta_value = filepath from joined table
So I have some questions:
How to make insert from joined table?
How to make while-like loop to insert every entry from joined table?
How to make n increment by 1 after every insert?
How to make insert from joined table?
Use a INSERT INTO .. SELECT FROM construct
How to make n increment by 1 after every insert?
Declare that column n as auto_increment column. Else, you will have to do it yourself if your concerned table already has a auto_increment column in place.
How to make while-like loop to insert every entry from joined table
You don't need that at all. INSERT .. SELECT construct will insert all the fetched rows to your referred table.
Your insert with select could be something like this:
insert into wordpress.table
SELECT (#i:=#i+1), nid, fifu_image_url, filepath
FROM drupal.content_field_image
JOIN drupal.files ON content_field_image.field_image_fid = files.fid;
join (select #i:=34) inc on true
To make it work, the columns of your select must have the same columns of the table you are inserting.
The incremental int could be made with this variable #i, initialized as 34 like you wanted and incremented 1 by 1 as the results as printed.

Creating a table on the basis of a field

I have a MySql table which has about 100k rows. there is one field say id which contains numbers from 1-35. all these records fall in this range of id i.e. all these records have value of id column between 1-35.
Now i want to create another table which will have one row of each id. i.e the new table should have 35 rows only.
How to go about it ?
create table new_table (id int);
insert into new_table
select distinct id from big_table;
Edit:
You can create the new_table by outputting the big_table create script and changing the name.
SHOW CREATE TABLE big_table;
/* modify the name of the output and execute */
insert into new_table
select * from big_table group by id
You have a table with 100.000 rows, and you want a new table with 35 rows. What values do you want for the remaining columns?
If the answer is: doesn't matter, this works:
CREATE TABLE newTable
SELECT * FROM yourTable
GROUP BY ID;
If you only want the IDs,
CREATE TABLE newTable
SELECT DISTINCT ID FROM yourTable;
You can copy data from one table to another even difference database(Schema) as following
INSERT INTO [DestDatabase].[DestTablName]
SELECT [ColumnName] FROM [SourceDatabase].[SourceTablName];
So, you can use two way:
1:
INSERT INTO tbl_New
SELECT DISTINCT id from tbl_Original;
2:
INSERT INTO tbl_New
SELECT id from tbl_Original GROUP BY id;

mySQL: 1)single column name aliased 2) adding virtual column

Two questions:
1)
There are several tables that are used as an archive for other tables.
To do so, there is a
INSERT INTO data_archive_table (SELECT * FROM data_table)
The problem is that the data_table.id should be kept as data_archive_table.old_id.
Is there a way to write a query that will look like: SELECT *, id AS old_id FROM data_table, while the results columns will have ONLY the old_data column, and NOT the original id column?
Using all column names is the only option I see, but I prefer to avoid it.
2)
I want to add a virtual column named deleted_time to the insertion query, that will hold the current time.
Can it be done? if so - how ?(tutorials will be great)
Try this:
1.) You can use something like this query:
INSERT INTO data_archive_table
SELECT id AS old_id -- be sure that data_archive_table has column oldID
,... -- You need to specify the names of the columns
FROM data_table
WHERE id = 'IDHERE' -- If you want to have condition.
2.) For this, you can add the value directly in you select statement
INSERT INTO `tableName`
SELECT colA,
colB,
, ...
, NOW() as deleted_time -- NOW() is a function in MySQL
FROM `sourceTable`
WHERE colA = 'IDHERE' -- If you want to have condition.
NOW() in MySQL

Assigning row rank numbers

I have a database. I want to update a column of it. The column should contain unique integer numbers in ascending order according to alphabetical order of another column.
Sorry not clear maybe, I want to have integer numbers like this:
1 ACC 501
2 BCC 501
3 GCC 601
4 FCC 601
Is there a reasonably simple way of setting this rank/order with mysql or sql query?
What you need is a ranking function which is not supported by MySQL at the moment. However, you can simulate them like so:
Set #rownum := 0;
Select rnk, SomeCode, SomeNum
From (
Select #rownum := #rownum + 1 As rnk, SomeCode, SomeNum
From MyTable
Order By SomeCode Asc
) As Z
Create another table that has the same schema as your original table, plus the new column. The new column should be an autonumber. Do an INSERT...SELECT into that table. The new column will be filled out with the values you want.
Like what Alex said, you want to create a new table like
CREATE TABLE newTable(
#Table definition from current table,
id INT NOT NULL AUTO_INCREMENT
);
And then insert with
INSERT INTO newTable
SELECT * FROM oldTable
ORDER BY orderColumn;
I think you can quickly do the create table with
CREATE TABLE newTable LIKE oldTable;
ALTER TABLE newTable ADD COLUMN id INT NOT NULL AUTO_INCREMENT;