SQL combining or,and query - mysql

I have one table called student.I want to select a student name who is living in chennai or madurai and born on december 8 1996.The table column name is (name,city,DOB). Sort the result by name. I have written like this and i got error "Invalid relational operator".
SELECT name
FROM student
WHERE city='chennai' OR 'madurai' AND DOB='december 8 1996'
ORDER BY name;

You have to mention the column in each where clause test.
Also if you are mixing AND and OR you need to apply some parenthasis to ensure they are applied correctly.
Also the date should be in yyyy-mm-dd format Assuming that you have deined DOB as a DATE type. And you should have if it is holding a date.
SELECT name
FROM student
WHERE (city='chennai' OR city='madurai' ) AND DOB='1996-12-08'
ORDER BY name;

Related

How to group by with 2 different field for the below criteria

Name date sellingAmt
Raju 08-02-2017 2000
Ravi 09-02-2017 5000
Ravi 09-02-2017 2000
Raju 09-02-2107 1000
Expected Result
Name date sellingAmt
Raju 08-02-2017 2000
Ravi 09-02-2017 7000
Raju 09-02-2107 1000
Let me know how to group by this in mysql select query
Seems like a pretty basic question. What part are you struggling with?
Always post what you've tried so we can look at your train of thought and try to correct the problem at it's root instead of giving you a baked solution!
Date (and I just see name is as well) is a keyword/reserved word so out of habit I use the ` to escape them.
I used sellingAmt Desc as the order by since it appears you want those within the same date; though you could just as easily want name desc.
I group by name, date to achieve the desired results. While mySQL extends the group by so you can group on fewer values than what is in the select, I find this feature is wrongly used more often than correctly. So I tend to error on the side of caution and always group by all fields not part of an aggregate; which is what other RDBMS systems would require of you. In your case date and name are the unique combination to sum sellingAmt correctly and achieve your expected results.
.
SELECT `Name`, `Date`, Sum(SellingAmt) sellingAmt
FROM {tblName}
GROUP BY `Name`, `Date`
ORDER BY `date`, sellingAmt Desc
Replace {tblname} with your table name.

MySql: How to display only 1 name only per multiple name

To make it more clear, If I have this data in MySql:
name | allowance | age
----------------------
khan | 50 | 20
aal | 60 | 22
hyme | 50 | 21
khan | 61 | 20
notice that there are two 'khan' in the database with different allowance. I want to only show the name and the age but if I show it using the mysqli select statement, there would be two 'khan' but I only want to show only 1 'khan'. How can I do it?
You need to use GROUP_CONCAT to see agges of all Khans;
select name, GROUP_CONCAT(age) ages from Table group by name
or for minimum aged khan
select name , min(age) MiniumAge from Table group by name
or for elder khan
select name , max(age) MaxAge from Table group by name
or any khan
select name , age from Table group by name
.
Please try below query:-
SELECT name, age FROM table_name WHERE group by name
If you want any from multiple same record then simply used group by query.
I think you could do this:
SELECT name, age FROM table_name WHERE group by name,age
First thing: if both those "khan"s are the same person with two different allowances then your schema is not properly normalized and it will give you big troubles later - imagine you want to change "khan" to "Khan" - now you have to update it in multiple places instead once. Depending on your actual needs you may want one table of people (person_id, name, age), and table of allowances (person_id, allowance, [..some other parameters?..]).
Second, to really get what you want, either you use group by, to get one "random" row per each name as suggested in other answers, or you can do
SELECT DISTINCT name, age FROM table;
which will give you one row per each name-age combination, so khan-20 will be there only once - but if there were khan-25 then that is probably different person and you would have two khans returned, each with their own age.
You can try this mate:
SELECT DISTINCT
name, age
FROM
<your_table>;
or this one
SELECT
name, age
FROM
<your_table>
GROUP BY
name;
Q: Is there any chance that if there are 2 records of tha same name have difference value of age? If so, kindly update the question so that better answers will be given. Cheers!

Find lowest value and coresponding code on asingle query mysql

I have a user table as follows
id name age
1 John 21
2. Mathan 23
3. Raj 21
4. Manoj 50
5 Krishnan 91
I want to find minimum age and its corresponding name. How can I do it with rails?
Can I do it in a single query?
Note: More than one names can have single age.
Is there a specific reason why you want to do it in a single query ?
If you can write 2 queries, I think you can just write :
User.where age: User.minimum(:age)
select age, group_concat(name) from table group by age order by age asc limit 1
You will need to process the results later on in ruby, but this gives all you need in one single query. Also i am assuming mysql, so might differ on other rdbms.
It gives exact output in mysql that you want try this
SELECT concat("[",name," ",age,"]") AS name
FROM TABLE
WHERE age =
(SELECT min(age)
FROM TABLE);

How to prioritize a LIKE query select based on string position in field?

I am attempting to query a table for a limited resultset in order to populate an autocomplete field in javascript. I am, therefore, using a LIKE operator with the partial string entered.
If I have, for example, a table such as:
tblPlaces
id country
1 Balanca
2 Cameroon
3 Canada
4 Cape Verde
5 Denmark
For the sake of this example, let's say I want two rows returning - and yeah, for this example, I made up a country there ;) I want to prioritize any instance where a partial string is matched at the beginning of country. The query I began using, therefore is:
SELECT id, country FROM tblPlaces WHERE country LIKE 'ca%' LIMIT 2
This returned 'Cameroon' and 'Canada' as expected. However, in instances where there are no two names in which the string is matched at the beginning of a word (such as 'de'), I want it to look elsewhere in the word. So I revised the query to become
SELECT id, country FROM tblPlaces WHERE country LIKE '%ca%' LIMIT 2
This then returned 'Cape Verde' and 'Denmark', but in doing so broke my original search for 'ca', which now returns 'Balanca' and 'Cameroon'.
So, my question is, how to go about this using a single query that will prioritize a match at the start of a word (perhaps I need to use REGEXP?) I am assuming also that if the 'country' column is indexed, these matches will at least be returned with subsequent alphabetical priority (i.e. Cameroon before Canada etc).
If you mean to prioritize matches that are Exactly at the start...
SELECT id, country
FROM tblPlaces
WHERE country LIKE '%ca%'
ORDER BY CASE WHEN country LIKE 'ca%' THEN 0 ELSE 1 END, country
LIMIT 2
EDIT
More generic and possibly faster (Assuming "closer to the start the 'better' the match")...
SELECT id, country
FROM tblPlaces
WHERE country LIKE '%ca%'
ORDER BY INSTR(country, 'ca'), country
LIMIT 2

How to get enum element from index

I have a select in which I do a "group by". One of the columns is an enum, and I want to select the biggest value for each group (i.e the one with the largest index in the enum). I can do
select MAX(enum_column+0) as enum_index
to get the the largest index in the group, but how can I turn the enum index back to the enum item?
Example:
Say I have a table "soldiers" with three columns:
"id" - soldier's ID
"name" is the soldier's first name (a varchar field).
"rank" is the soldier's rank, and it is an enum:
{'private','sergent'...,'lieutenant' etc.}
Now suppose I want to find for each first name, the the highest rank a person with that name has.
I can do:
select MAX(rank+0) as enum_index,name from soldiers group by name
But that will give me the index of the max element in the enum field, and not the name of the element. I.e it will give me:
1 | john
2 | bob
where I want
'private' | john
'sergent' | bob
How can I achieve the desired result?
Run the following
CREATE TABLE ranks
SELECT DISTINCT rank+0 as id, CONCAT('',rank) as rank
FROM soldiers
Then join the data with the soldiers table. Notice it will give you only the ranks actually in use.
SUBSTR( MAX(CONCAT(0+column, column)), 2)
The concat will generate items like 0private or 1sergeant; these will be sorted as strings when taking the MAX. In this case this is the same as sorting by enum order. Finally the initial digit is removed by the substr.
If you have more than 10 items in your enum you'll have to format the numeric value with leading digits and remove the additional digits in the substr call.