Fix the order of auto_incremented keys mysql database - mysql

I have a MySQL table which has a primary key book_num which is being auto_incremented, problem is that I had deleted some books from it and then inserted more books and so through an interface, so if the book with book_num = 4 was deleted now the table is missing book_num 4. so it would be like 1, 2, 3 and then 5 how can i make it so that missing spot just get covered like since there are 4 rows with column book_num 1, 2, 3, 4, not skipping the 4 like 1, 2, 3, 5. I can duplicate a table just like the original one and then insert all values from that table to the new table so there no skipping like that but I was wondering if there is a MySQL command to do that. Here is the actual table which is missing the number 79 because I deleted that book.
+----------+----------------------------------------------------------+
| book_num | book_name |
+----------+----------------------------------------------------------+
| 74 | MySQL Cookbook |
| 75 | PHP Cookbook |
| 76 | Learn to Program with Python |
| 77 | THE MIT ENCYCLOPEDIA OF THE COGNITIVE SCIENCES |
| 78 | Microsoft Visual C++/CLI Step by Step |
| 80 | Advanced Problems in Core Mathematics |
| 81 | The C+ + Programming Language |
| 82 | Design Patterns : Elements of Reusable Object-Oriented S |
| 83 | Developing Concepts in Applied Intelligence |
You see the 79 is missing is there a way to push all the indexes after 78 up there by filling the gap of 79. so like after 78 it shows:
| 79 | Advanced Problems in Core Mathematics |
and so forth.

Related

How do I store array of integers in vertica database?

Currently I'm working on vertica database.
I'm facing problem while storing array of integers in one column. I imported data values through csv.
I used the following code to create table.
CREATE TABLE testing_table_1 (email varchar,name varchar,gen int,yob int,ct int,cy int,a varchar(65000),b varchar(65000),c varchar(65000));
I imported data with the following code.
COPY testing_table_1 from '/home/naresh/Desktop/bigfile.csv' parser fcsvparser();
My sample CSV format looks like the below.
ghchnu#tly.org.cn | Donald Garcia | 2 | 2003 | 21947 | 91 | 241,127,225,68,162 | 4,84,63,69,15 | 32,44,15,31
rlmx#jyqewy.biz | Charles Brown | 2 | 2012 | 22218 | 45 | 127,156,186,136,242 | 49,69,14,80,95,1 | 39,36,38,40,20
7th,8th and 9th columns are storing in the format of a string.
But what I want is, I want them to be stored in an array of integers format.
Because of the string format I am unable to perform combination of integers operation using 'IN' query.
I don't to want to use flex-table format in vertica.
Give suggestions other than flex-table format.
Please give me a possible solution for the above problem.
Please correct me if I am doing any mistake.
Thanks in advance,
Vertica is a real, SQL based, relational database.
And those actually do not have rows with a variable number of columns - which is what using arrays would boil down to.
What you need to do is to make, out of this:
[...] 91 | 241,127,225,68,162 | 4,84,63,69,15 | 32,44,15,31
This:
[...] 91 | 1 | 241 | 4 | 32
[...] 91 | 2 | 127 | 84 | 44
[...] 91 | 3 | 225 | 63 | 15
[...] 91 | 4 | 68 | 69 | 31
[...] 91 | 5 | 162 | 15 |(null)
Check out the SPLIT_PART() function; you might want to run it with 1,2,3,4 and finally 5 as the third parameter, and use that very number as the key that you see in the second displayed column above. To get the resulting column as integers, cast the strings that come out of the SPLIT_PART() function to integers.
Good luck -
Marco

how should I build up my database when I want to store these kind of data?

I want to build a page like shown below and all data should be retrieved from a database. Both the term, subject and sentences is retrieved from a database. Three levels of data. And under each term (eg. Spring 2017) I can pick and choose between all of these sentences.
Spring 2017
Subject1
Sentence 1
Sentence 2
Sentence 3
Subject2
Sentence 13
Sentence 12
Sentence 17
Subject3
Sentence 11
Sentence 14
Sentence 19
Autmn 2017
...
I want to present similar info from database to user, and let the user choose between all this sentences. How should i build up my database for achieving this in the best and most efficient way.
One way is:
Table 'subject' Table 'sentences'
| id | subjects | | id | subjectid | name |
| 3 | Subject1 | | 1 | 3 | Sentence 2 |
| 4 | Subject2 | | 2 | 4 | Sentence 13 |
Table 'term'
| id | term | sentenceid |
| 1 | Spring 17 | 1,2,28 |
Another way is maybe using pivot-tables, something like this:
Table 'sentences'
| id | parentid | name |
| 1 | 0 | Subject2 |
| 2 | 3 | Sentence 2 |
| 3 | 0 | Subject1 |
| 4 | 1 | Sentence 13 |
Table 'term'
| id | term | sentenceid |
| 1 | Spring 17 | 2,4,28 |
Notice: Number of terms can be many more than just two in a year.
Is it any of this structures you recommend, or any other way you think I should build my database? Is one of these more efficient? Not so demanding? Easier to adjust?
You are doing relational analysis/design:
Find all substantives/nouns of your domain. These are candidates for tables.
Find any relationships/associations between those substantives. "Has", "consists of", "belongs to", "depends on" and so on. Divide them into 1:1, 1:n, n:m associations.
look hard at the 1:1 ones and check if you can reduce two of your original tables into one.
the 1:n lead you to foreign keys in one of the tables.
the n:m give you additional association tables, possibly with their own attributes.
That's about it. I would strongly advise against optimizing for speed or space at this point. Any modem RDBMS will be totally indifferent against the number of rows you are likely to encounter in your example. All database related software (ORMs etc.) expect such a clean model. Packing ids into comma separated fields is an absolutes no-no as it defeats all mechanisms your RDBMS has to deal with such data; it makes the application harder to program; it confuses GUIs and so on.
Making weird choices in your table setup so they deviate from a clean model of your domain is the #1 cause of trouble along the way. You can optimize for performance later, if and when you actually get into trouble. Except for extreme cases (huge data sets or throughput), such optimisation primarily takes place inside the RDBMS (indexes, storage parameters, buffer management etc.) or by optimizing your queries, not by changing the tables.
If the data is hierarchical, consider representing it with a single table, with one column referencing a simple lookup for the "entry type".
Table AcademicEntry
================================
| ID | EntryTypeID | ParentAcademicEntryID | Description |
==========================================================
| 1 | 3 | 3 | Sentence 1 |
| 2 | 1 | <null> | Spring 2017 |
| 3 | 2 | 2 | Subject1 |
Table EntryType
================================
| ID | Description |
====================
| 1 | Semester |
| 2 | Subject |
| 3 | Sentence |
Start with the terms. Every term has subjects. Every subject has sentences. Then you may need the position of a subject within a term and probably the position of a sentence in a subject.
Table 'term'
id | term
---+------------
1 | Spring 2017
Table 'subject'
id | title | termid | pos
---+----------+--------+----
3 | Subject1 | 1 | 1
4 | Subject2 | 1 | 2
5 | Subject3 | 1 | 3
Table 'sentence'
id | name | subjectid | pos
---+-------------+-----------+-----
1 | Sentence 2 | 3 | 2
2 | Sentence 13 | 4 | 1
3 | Sentence 1 | 3 | 1
4 | Sentence 3 | 3 | 3
2 | Sentence 17 | 4 | 3
...
This table design Should resolve your need.
TblSeason
(
SeasonId int,
SeasonName varchar(30)
)
tblSubject
(
Subjectid int
sessionid int (fk to tblsession)
SubjectData varchar(max)
)
tblSentences
(
SentencesID INT
Subjectid int (Fk to tblSubject)
SentenceData varchar(max)
)

Get Number of A's in Result Table - MySQL

This is the case. In my school all classes prepare excel sheet for each class with marks for each subject in term end test. There are 17 classes. I combine them in to access table. Then again export all data in to excel. make csv file . And import to Mysql Database using phpmyadmin. now I have result table as follow.
| ID | Name | Religion | Sinhala | science | english | maths | History | Categery 1 | Categery 2 | Categery 3 | Total | Average | Rank | |
|---- |------- |---------- |--------- |--------- |--------- |------- |--------- |------------ |------------ |------------ |------- |--------- |------ |--- |
| 1 | manoj | 45 | 65 | 78 | 98 | 67 | 67 | 63 | 76 | 64 | 654 | 62 | 12 | |
Sectional Head Need to get number of students who got >75 for all Subject.
And Number of Student Who got >75 for 8 subject out of 9.
I need to retrieve number of A s, B s (marks >=75) from this table.
Ex. Student names and Number of A s
Total Number of A for all 9 subject - 45
Total Number of A for all 8 subject (any 8 subject ) - 45
Total Number of A for all 7 subject (any 7 subject ) - 45
I Tried following SQL Statement
SELECT COUNT(SELECT COUNT()
FROM result
WHERE religion >=75
AND Math >=75)
FROM result
I read about same scenario in stack overflow.
Access 2010
this one get some point. but I cant solve it for my scenario.
Use GROUP BY studentName and SUM(grade = 'A') AS numberOfAs.
[Quick answer bc question is quickly formatted]

Convert Mysql Query to Rails ActiveRecord Query Without using find_by_sql

I have table named questions like follows
+----+---------------------------------------------------------+----------+
| id | title | category |
+----+---------------------------------------------------------+----------+
| 89 | Tinker or work with your hands? | 2 |
| 54 | Sketch, draw, paint? | 3 |
| 53 | Express yourself clearly? | 4 |
| 77 | Keep accurate records? | 6 |
| 32 | Efficient? | 6 |
| 52 | Make original crafts, dinners, school or work projects? | 3 |
| 70 | Be elected to office or make your opinions heard? | 5 |
| 78 | Take photographs? | 3 |
| 84 | Start your own political campaign? | 5 |
| 9 | Free spirit or a rebel? | 3 |
| 38 | Lead a group? | 5 |
| 71 | Work in groups? | 4 |
| 2 | Helpful? | 4 |
| 4 | Mechanical? | 6 |
| 14 | Responsible? | 6 |
| 66 | Pitch a tent, an idea? | 1 |
| 62 | Write useful business letters? | 5 |
| 28 | Creative? | 3 |
| 68 | Perform experiments? | 2 |
| 10 | Like to figure things out? | 2 |
+----+---------------------------------------------------------+----------+
I have a sql query to get one random record from each category.Can any one convert the mysql query to rails activerecord query(with out using Question.find_by_sql).This mysql query is working absolutely fine but I need only active record query because of my dependency in further steps.
Here is mysql query
SELECT t.id, title as question, category
FROM
(
SELECT
(
SELECT id
FROM questions
WHERE category = t.category
ORDER BY RAND()
LIMIT 1
) id
FROM questions t
GROUP BY category
) q JOIN questions t
ON q.id = t.id
Thank You for your consideration!
When things get crazy one have to reach out for Arel:
It is intended to be a framework framework; that is, you can build
your own ORM with it, focusing on innovative object and collection
modeling as opposed to database compatibility and query generation.
So what we want to do is to let Arel create the query for us. Moreover the approach here is gonna be used: the questions table is left joined with randomized version of itself:
q_normal = Arel::Table.new("questions")
q_random = Arel::Table.new("questions").project(Arel.sql("*")).order("RAND()").as("q2")
Time to left join
query = q_normal.join(q_random, Arel::Nodes::OuterJoin).on(q_normal[:category].eq(q_random[:category])).group(q_normal[:category]).order(q_random[:category])
Now you can use which columns you want using project, e.g.:
query.project(q_normal[:id])
The only way I can think of to do this requires a good bit of application code. I don't think there's a way of accessing the RAND() functionality in MySQL (or equivalent in other DB technologies) using ActiveRecord. Here's what I came up with:
counts = Question.group(:category_id).count(:id)
offsets = {}
counts.each do |cat_id, count|
offsets[cat_id] = rand(count)
end
random_questions = []
offsets.each do |cat_id, offset|
random_questions.push(Question.where(:category_id => cat_id).offset(offset).first)
end

Erasing duplicate records from MySQL

Due to a bug in my javascript click handling, multiple Location objects are posted to a JSON array that is sent to the server. I think I know how to fix that bug, but I'd also like to implement a server side database duplicate erase function. However, I'm not sure how to write this query.
The only affected table is laid out as
+----+------------+--------+
| ID | locationID | linkID |
+----+------------+--------+
| 64 | 13 | 14 |
| 65 | 14 | 13 |
| 66 | 14 | 15 |
| 67 | 15 | 14 |
| 68 | 15 | 16 |
| 69 | 16 | 17 |
| 70 | 16 | 14 |
| 71 | 17 | 16 |
| 72 | 17 | 16 |
| 73 | 17 | 16 |
| 74 | 17 | 16 |
| 75 | 17 | 16 |
| 76 | 17 | 16 |
| 77 | 17 | 16 |
+----+------------+--------+
As you can see, I have multiple pairs of (17, 16), while 14 has two pairs of (14, 13) and (14, 15). How can I delete all but one record of any duplicate entries?
Don't implement post factum correction logic, put a unique index on the fields that need to be unique, that way the database will stop dupe inserts before it's too late.
If you're using MySQL 5.1 or higher you can remove dupes and create a unique index in 1 command:
ALTER IGNORE TABLE 'YOURTABLE'
ADD UNIQUE INDEX somefancynamefortheindex (locationID, linkID)
You can create a temporary table where you can store the distinct records and then truncate the original table and insert data from temp table.
CREATE TEMPORARY TABLE temp_table (locationId INT,linkID INT)
INSERT INTO temp_table (locationId,linkId) SELECT DISTINCT locationId,linkId FROM table1;
DELETE from table1;
INSERT INTO table1 (locationId,linkId) SELECT * FROM temp_table ;
delete from tbl
using tbl,tbl t2
where tbl.locationID=t2.locationID
and tbl.linkID=t2.linkID
and tbl.ID>t2.ID
I am assuming you don't mean for the clean up, but for the new check? Put a unique index on if possible, if you don't have control of the DB do an upsert and check for nulls instead of an insert.