MySql Query regarding use of TOP command - mysql

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '(2) from empdata where empid='E-713'' at line 1
mysql> delete TOP(2) from empdata where empid='E-713';
+-------+--------+--------+--------+------+---------+
| id | name | height | salary | age | city |
+-------+--------+--------+--------+------+---------+
| E-713 | Rajat | 5.11 | 25000 | 25 | jaipur |
| E-720 | Ritesh | 5.8 | 30000 | 27 | Delhi |
| E-711 | Javed | 5.7 | 23000 | 25 | kashmir |
| E-715 | Puneet | 5.1 | 20000 | 27 | Noida |
| E-713 | Rajat | 5.11 | 25000 | 25 | jaipur |
+-------+--------+--------+--------+------+---------+
How can I get nth highest salary using top command in MySql. although my syntax is correct as per my knowledge but on pressing enter the above error flashed.

This is a bit long for a comment.
MySQL does not support SELECT TOP. That is usually associated with SQL Server.
It does support LIMIT, so you could write:
delete ed
from empdata ed
where empid = 'E-713'
limit 2;
However, this is very dangerous, because it deletes two arbitrary rows. In almost all cases, you want an ORDER BY:
delete ed
from empdata ed
where empid = 'E-713'
order by ??
limit 2;
This is true whether you are using TOP or LIMIT.

Related

How to get the last 3 rows from MYSQL database

I wanted to get only the last 3 rows of my database here is the query that I tried
select top 3 * from poem where MemberID = 54;
But there was an error
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '3 * from poem where MemberID = 54' at line 1
This is an example of one of the data stored in my table poem
MariaDB [bigproject]> select PoemID, Title, Description from poem where MemberID = 79;
+--------+------------------------+--------------------+
| PoemID | Title | Description |
+--------+------------------------+--------------------+
| 34 | Everything Has Changed | EHC |
| 52 | Kapono | Poetic |
| 53 | Love under the sky | How is your heart? |
| 54 | Imaginary | Imagine me |
+--------+------------------------+--------------------+
4 rows in set (0.000 sec)
I only wanted to get the last 3 rows of this.
Thank you!!

SQL join several tables based on latest entry in transaction table per join record

I have a transaction table with timestamps
a transaction has one event and one user.
All transactions have an event,
All events have at least one trasaction,
Each transaction has a user that must exist,
A User will not necessarily have a transaction.
The output will be a sort of the evt list
Output line count should equal db.evt record count.
The first column of each table is the Autoinc unique index.
In transaction, these are fks to the other tables.
The problem is that I need the transaction with the latest timestamp for the evt in the transaction table.
I am still relatively new to SQL (Using MySQL) and while I muddle through joins. I have no idea how to get the latest record by evID by timestamp.
I have looked at other questions on the topic but not found one that addresses mine. (Granted there are 14K on Joins alone, so I may have missed one)
Sample Table Data below:
Table structure is hopefully obvious by I will edit it in if requested.
Edit:
I've changed the names of tables and columns for clarity (and to avoid matching keywords)
I tried Stuart's answer below and got an error:
Answer:
SELECT
eventTable.EvtName AS EvtD,
transTable.TranAct AS LastTrans,
userTable.UserName AS UsrNm
FROM
transTables,
INNER JOIN (
SELECT evtID, MAX(TransID) TransID FROM transTable GROUP BY evtID
) last ON last.evtID = transTable.evtID AND last.TransID = transTable.TransID
INNER JOIN eventTable ON eventTable.evtID = transTable.evtID
INNER JOIN userTable ON userTable.usId = transTable.usId
Response:
#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near
'INNER JOIN (
SELECT evtID, MAX(TransID) TransID FROM transTable GROUP BY evt'
at line 7
Tables:
db.transTable
| TransID | EvtID | TranAct | timestamp | UserID
----------------------------------------------------------------
| 1 | 1 | add | 2014-05-08 08:10:00.000 | 3
| 2 | 2 | add | 2014-05-08 09:10:00.000 | 2
| 3 | 3 | add | 2014-05-08 10:10:00.000 | 3
| 4 | 2 | validate | 2014-05-08 11:10:00.000 | 5
| 5 | 3 | validate | 2014-05-08 12:10:00.000 | 3
| 6 | 2 | reverse | 2014-05-08 13:10:00.000 | 1
| 7 | 1 | edit | 2014-05-08 14:10:00.000 | 4
| 8 | 4 | add | 2014-05-08 15:10:00.000 | 3
| 9 | 5 | add | 2014-05-08 16:10:00.000 | 2
db.eventTable
| EvtID | EvtName
-----------------
| 1 | Evt1
| 2 | Evt2
| 3 | Evt3
| 4 | Evt4
| 5 | Evt5
db.userTable
| UserID | UserName
--------------------
| 1 | Usr1
| 2 | Usr2
| 3 | Usr3
| 4 | Usr4
| 5 | Usr5
Desired output:
eventTable.EvtName AS EvtD
transTable.TranAct AS LastTrans
userTable.UserName AS UsrNm
| EvtD | LastTrans | UsrNm
--------------------------
| Evt1 | edit | Usr4
| Evt2 | reverse | Usr1
| Evt3 | validate | Usr3
| Evt4 | add | Usr3
| Evt5 | add | Usr2
Much thanks for any assistance.
Something like this shuold work where a derived table is used to eliminate all transactions except the latest per evId.
SELECT
eventTable.EvtName AS EvtD,
transTable.TranAct AS LastTrans,
userTable.UserName AS UsrNm,
FROM
transTable
INNER JOIN (
SELECT evId, MAX(UID) uid FROM transTable GROUP BY evId
) last ON last.evId = transTable.evId AND last.uid = transTable.uid
INNER JOIN eventTable ON eventTable.evId = transTable.evId
INNER JOIN userTable ON userTable.usId = transTable.usId

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

mysql search query for 2 columns with single parameter

I am new to databases. In mysql database I have one table course. My question is: how to search all related words in both columns course_name and course_description and i need to get all the matched words in both columns? Can any one tell me the sql query for it? I have tried to write a query, but I am getting some syntax errors.
+----------+-----------+-----------------+------------+------------+
| courseId | cname | cdesc | sdate | edate |
+----------+-----------+-----------------+------------+------------+
| 301 | physics | science | 2013-01-03 | 2013-01-06 |
| 303 | chemistry | science | 2013-01-09 | 2013-01-09 |
| 402 | afm | finanace | 2013-01-18 | 2013-01-25 |
| 403 | English | language | 2013-01-17 | 2013-01-24 |
| 404 | Telugu | spoken language | 2013-01-10 | 2013-01-22 |
+----------+-----------+-----------------+------------+------------+
SELECT * from course WHERE cname='%searchtermhere%' AND cdesc='%searchtermhere%'
Adding the percent % makes the search within each value and not just beginning with.
If you want to search exact word
SELECT * FROM course WHERE cname ='word' AND cdesc = 'word'
OR you can also find each value and not just start from begining.
SELECT * FROM course WHERE cname = '".%searchtermhere%."' AND cdesc = '".%searchtermhere%."'
Since you say single parameter i guess. You will get either 'science' as input or 'physics' as input. Then you could simply use 'OR'.
select * from course where cname = (Input) or cdesc = (Input)

How do I get rhe right syntax for searching a string in a database table?

List the state descriptions that start with “NEW” and the count of the employers located in that state. Be sure to list all of those states that start with “NEW” even if the count is zero. Make sure your column headings match what is shown below.
+---------------+---------------------+
| Description | Number of Companies |
+---------------+---------------------+
| NEW HAMPSHIRE | 0 |
| NEW JERSEY | 1 |
| NEW MEXICO | 0 |
| NEW YORK | 13 |
+---------------+---------------------+
4 rows in set (0.00 sec)
For this question I used:
SELECT state.description, COUNT(*) "Number of Commpanies"
FROM employer
WHERE SUBSTR(state.description, 1, INSTR(state.description, 'NEW')-1) AS "Number of Companies";
ERROR:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'AS "N
umber of Companies"' at line 3
Why am I getting this and what is the right syntax. First of all, I'm not sure if I'm following the question correctly. The table as follows:
mysql> DESCRIBE state;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| statecode | char(2) | | PRI | | |
| description | varchar(30) | | | | |
+-------------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec) mysql>
mysql>SELECT * FROM employer
| companyname | division | address | city | statecode | zipcode |
| Acme Information Source | Customer Support | 132 Commerical Way | Cleveland | OH | 44234 |
| Ajax Software, Inc. | RandD | 2421 West Industrial Way | Berkeley | CA | 94710 |
| Ajax Software, Inc. | Production | 2421 West Industrial Way | Berkeley | CA | 94710 |
The correct syntax for a column alias is:
SELECT state.description, COUNT(*) AS "Number of Companies"
FROM employer
WHERE .. -- your logic here
You can't add a column alias after the WHERE, that doesn't make sense.
However, you have a way to go to actually answering the question. You refer to the state table, but you're not joining to it yet, for example.
A where clause has to resemble
where something = something
Yours resembles
where something as alias name
However, the simple answer is:
where state.description like 'NEW%'
Try the following:
SELECT s.description, count(e.*) as "Number of Companies"
FROM employer e left join state s on e.statecode = s.statecode
WHERE s.description like 'NEW%'
GROUP by 1
Use a JOIN, and you were missing a GROUP BY
SELECT
s.description,
COUNT(*) AS "Number of Companies"
FROM state a
JOIN employer e ON s.statecode = e.statecode
WHERE s.description LIKE 'NEW%'
GROUP BY 1