I have 9 fields and I need to see all the data from these fields which have a particular set of IDs. Could any one tell me the SQL query for it?
Ex: Database contains 100 records. I need to select a list of 20 IDs from the field BusID and it's corresponding rows.
SELECT *
FROM `Buses`
WHERE `BusID` I am stuck after this.. how do I put in the list of 20 BusIds here?
If you know the list of ids try this query:
SELECT * FROM `Buses` WHERE BusId IN (`list of busIds`)
or if you pull them from another table list of busIds could be another subquery:
SELECT * FROM `Buses` WHERE BusId IN (SELECT SomeId from OtherTable WHERE something = somethingElse)
If you need to compare to another table you need a join:
SELECT * FROM `Buses` JOIN OtheTable on Buses.BusesId = OtehrTable.BusesId
You can try this
SELECT * FROM Buses WHERE BusID in (1,2,3,4,...)
I strongly recommend using lowercase field|column names, it will make your life easier.
Let's assume you have a table called users with the following definition and records:
id|firstname|lastname|username |password
1 |joe |doe |joe.doe#email.com |1234
2 |jane |doe |jane.doe#email.com |12345
3 |johnny |doe |johnny.doe#email.com|123456
let's say you want to get all records from table users, then you do:
SELECT * FROM users;
Now let's assume you want to select all records from table users, but you're interested only in the fields id, firstname and lastname, thus ignoring username and password:
SELECT id, firstname, lastname FROM users;
Now we get at the point where you want to retrieve records based on condition(s), what you need to do is to add the WHERE clause, let's say we want to select from users only those that have username = joe.doe#email.com and password = 1234, what you do is:
SELECT * FROM users
WHERE ( ( username = 'joe.doe#email.com' ) AND ( password = '1234' ) );
But what if you need only the id of a record with username = joe.doe#email.com and password = 1234? then you do:
SELECT id FROM users
WHERE ( ( username = 'joe.doe#email.com' ) AND ( password = '1234' ) );
Now to get to your question, as others before me answered you can use the IN clause:
SELECT * FROM users
WHERE ( id IN (1,2,..,n) );
or, if you wish to limit to a list of records between id 20 and id 40, then you can easily write:
SELECT * FROM users
WHERE ( ( id >= 20 ) AND ( id <= 40 ) );
I hope this gives a better understanding.
You're looking for the IN() clause:
SELECT * FROM `Buses` WHERE `BusID` IN (1,2,3,5,7,9,11,44,88,etc...);
Try the following code:
SELECT *
FROM users
WHERE firstname IN ('joe','jane');
You want to add the IN() clause to your WHERE
SELECT *
FROM `Buses`
WHERE `BusID` IN (Id1, ID2, ID3,.... put your ids here)
If you have a list of Ids stored in a table you can also do this:
SELECT *
FROM `Buses`
WHERE `BusID` IN (SELECT Id FROM table)
I have 3 fields to fetch from Oracle Database,Which is for Forex and Currency Application.
SELECT BUY.RATE FROM FRBU.CURRENCY WHERE CURRENCY.MARKET =10 AND CURRENCY.CODE IN (‘USD’, ’AUD’, ‘SGD’)
Related
i have a table
users
id collection_id
1 xwkoss
2 cw2333
3 oipopp
And i run query:
SELECT * FROM USERS WHERE collection_id in ('xwkoss','cw2333', 'abcdeef')
that query work fine and return 2 values existing on table, but i need know, which value doesn't exist on table records example: 'abcdeef', based on search parameters
thanks
Create a table on-the-fly and check with NOT EXISTS:
SELECT user_code
FROM
(
SELECT 'xwkoss' AS user_code
UNION ALL
SELECT 'cw2333' AS user_code
UNION ALL
SELECT 'abcdeef' AS user_code
) codes
WHERE NOT EXISTS
(
SELECT NULL
FROM users
WHERE users.user_code = codes.user_code
)
ORDER BY user_code;
I have two Tables [Users] and [Teams]. My Users Table looks like this [ID][E-Mail]. My Teams Table looks like this [Team][UserID].
I need to do a Subselect like this:
SELECT * FROM users WHERE 'ID' != (SELECT UserID FROM teams)
The Problem is that the Subselect returns multiple values. So i cannot compare it like this.
What i want to achive:
I want the Data from the User who IS NOT listed in the Table [Teams].
Example:
Table [Users] | Table[Teams] |
-------------- ------------------
[ID] [E-Mail] [UserID] [Team]
1 example1#google.com | 1 Football
2 example2#google.com | 1 Basketball
3 example3#google.com | 2 Basketball
So as you can see there are 3 exisiting Users, but the third User is not listed in the Table[Teams]. I want the E-Mail from the User, because he is not in any of these teams.
How could i accomplish that?
Instead of != use NOT IN:
SELECT * FROM users WHERE ID NOT IN (SELECT UserID FROM teams WHERE UserID IS NOT NULL)
Notice the UserID IS NOT NULL in sub query... NOT IN would fail if sub query returns one or more NULL values.
you can have multiple ways to implement the same
the below is one of the way
SELECT *
FROM users
WHERE ID NOT IN (SELECT UserID FROM teams)
We could also use an EXISTS clause:
SELECT *
FROM users u
WHERE NOT EXISTS (SELECT 1 FROM teams t WHERE u.ID = t.UserID);
Hello – I have a DB table (MySQL ver 5.6.41-84.1-log) that has about 92,000 entries, with columns for:
id (incremental unique ID)
post_type (not important)
post_id (not important, but shows relation to another table)
user_id (not important)
vote (not important)
ip (IP Address, ie. 123.123.123.123)
voted (Datestamp in GMT, ie. 2018-12-03 04:50:05)
I recently ran a contest and we had a rule that no single IP could vote more than 60 times per day. So now I need to run a custom SQL formula that applies the following rule:
For each IP address, for each day, if there are > 60 rows, delete those additional rows.
Thank you for your help!
This is a complicated one, and I think it is hard to provide a 100% sure answer without actual table and data to play with.
However let me try to describe the logic, and build the query step by step so you can paly around with it and possibly fix lurking erros.
1) We start with selecting all ip adresses that posted more than 60 votes on a given day. For this we use a group by on the voting day and on the ip adress, combined with a having clause
select date(voted), ip_adress
from table
group by date(voted), ip_adress
having count(*) > 60
2) From then, we go back to the table and select the first 60 ids corresponding to each voting day / ip adress couple. id is an autoincremented field so we just sort using this field and the use the mysql limit instruction
select id, ip_adress, date(voted) as day_voted
from table
where ip_adress, date(voted) in (
select date(voted), ip_adress
from table
group by date(voted), ip_adress
having count(*) > 60
)
order by id
limit 60
3) Finally, we go back once again to the table and search for the all ids whose ip adress and day of vote belong to the above list, but whose id is greater than the max id of the list. This is achieved with a join and requires a group by clause.
select t1.id
from
table t1
join (
select id, ip_adress, date(voted) as day_voted
from table
where ip_adress, date(voted) in (
select date(voted), ip_adress
from table
group by date(voted), ip_adress
having count(*) > 60
)
order by id
limit 60
) t2
on t1.ip_adress = t2.ip_adress
and date(t1.voted) = t2.day_voted and t1.id > max(t2.id)
group by t1.id
That should return the list of all ids that we need to delete. Test if before you go further.
4) The very last step is to delete those ids. There are limitations in mysql that make a delete with subquery condition quite uneasy to achieve. See the following SO question for more information on the technical background. You can either use a temporary table to store the selected ids, or try to outsmart mysql by wrapping the subquery and aliasing it. Let us try with the second option :
delete t.* from table t where id in ( select id from (
select t1.id
from
table t1
join (
select id, ip_adress, date(voted) as day_voted
from table
where ip_adress, date(voted) in (
select date(voted), ip_adress
from table
group by date(voted), ip_adress
having count(*) > 60
)
order by id
limit 60
) t2
on t1.ip_adress = t2.ip_adress
and date(t1.voted) = t2.day_voted
and t1.id > max(t2.id)
group by t1.id
) x );
Hope this helps !
You could approach this by vastly simplifying your sample data and using row number simulation for mysql version prior to 8.0 or window function for versions 8.0 or above. I assume you are not on version 8 or above in the following example
drop table if exists t;
create table t(id int auto_increment primary key,ip varchar(2));
insert into t (ip) values
(1),(1),(3),(3),
(2),
(3),(3),(1),(2);
delete t1 from t t1 join
(
select id,rownumber from
(
select t.*,
if(ip <> #p,#r:=1,#r:=#r+1) rownumber,
#p:=ip p
from t
cross join (select #r:=0,#p:=0) r
order by ip,id
)s
where rownumber > 2
) a on a.id = t1.id;
Working in to out the sub query s allocates a row number per ip, sub query a then picks row numbers > 2 and the outer multi-table delete deletes from t joined to a to give
+----+------+
| id | ip |
+----+------+
| 1 | 1 |
| 2 | 1 |
| 3 | 3 |
| 4 | 3 |
| 5 | 2 |
| 9 | 2 |
+----+------+
6 rows in set (0.00 sec)
I had someone help me write the following query, which addressed my question.
SET SQL_SAFE_UPDATES = 0;
create table temp( SELECT id, ip, voted
FROM
(SELECT id, ip, voted,
#ip_rank := IF(#current_ip = ip, #ip_rank + 1, 1) AS ip_rank,
#current_ip := ip
FROM `table_name` where ip in (SELECT ip from `table_name` group by date(voted),ip having count(*) >60)
ORDER BY ip, voted desc
) ranked
WHERE ip_rank <= 2);
DELETE FROM `table_name`
WHERE id not in (select id from temp) and ip in (select ip from temp);
drop table temp;
let's say I have the following Table:
ID, Name
1, John
2, Jim
3, Steve
4, Tom
I run the following query
SELECT Id FROM Table WHERE NAME IN ('John', 'Jim', 'Bill');
I want to get something like:
ID
1
2
NULL or 0
Is it possible?
How about this?
SELECT Id FROM Table WHERE NAME IN ('John', 'Jim', 'Bill')
UNION
SELECT null;
Start by creating a subquery of names you're looking for, then left join the subquery to your table:
SELECT myTable.ID
FROM (
SELECT 'John' AS Name
UNION SELECT 'Jim'
UNION SELECT 'Bill'
) NameList
LEFT JOIN myTable ON NameList.Name = myTable.Name
This will return null for each name that isn't found. To return a zero instead, just start the query with SELECT COALESCE(myTable.ID, 0) instead of SELECT myTable.ID.
There's a SQL Fiddle here.
The question is a bit confusing. "IN" is a valid operator in SQL and it means a match with any of the values (see here ):
SELECT Id FROM Table WHERE NAME IN ('John', 'Jim', 'Bill');
Is the same as:
SELECT Id FROM Table WHERE NAME = 'John' OR NAME = 'Jim' OR NAME = 'Bill';
In your answer you seem to want the replies for each of the values, in order. This is accomplished by joining the results with UNION ALL (only UNION eliminates duplicates and can change the order):
SELECT max(Id) FROM Table WHERE NAME = 'John' UNION ALL
SELECT max(Id) FROM Table WHERE NAME = 'Jim' UNION ALL
SELECT max(Id) FROM Table WHERE NAME = 'Bill';
The above will return 1 Id (the max) if there are matches and NULL if there are none (e.g. for Bill). Note that in general you can have more than one row matching some of the names in your list, I used "max" to select one, you may be better of in keeping the loop on the values outside the query or in using the (ID, Name) table in a join with other tables in your database, instead of making the list of ID and then using it.
I have a table student like this
id | name | zip
1 | abc | 1234
2 | xyz | 4321
3 | asd | 1234
I want to get all records but zip code should not be repeated. So In case of above table records, record No 1 and 2 should be fetched. Record No. 3 will not be fetched because it has a zip code which is already in record No. 1
SELECT DISTINCT fieldName FROM tableName;
The following query will only select distinct 'zip' field.
SELECT DISTINCT zip FROM student;
SELECT * FROM tableName GROUP BY fieldName;
The following query will select all fields along with distinct zip field.
SELECT * FROM student GROUP BY zip;
TRY
SELECT DISTINCT(zip),id,name FROM student;
OR
SELECT * FROM student GROUP BY zip;
Altough in MySQL you can get away with:
SELECT *
FROM student
GROUP BY zip
I would choose:
SELECT *
FROM student t
JOIN
( SELECT MIN(id) AS minid
FROM student
GROUP BY zip
) AS grp
ON grp.minid = t.id
Since presumably the other columns are of some interest....
SELECT y.*
FROM yourTable y,
(SELECT MIN(y2.id)
FROM yourTable y2
GROUP BY y2.zip) ilv
WHERE ilv.id=y.id;
(or you could use the max-concat trick)
update
Oracle have now removed the max concat trick from the linked page - but it is described elsewhere on the internet
Try Using
Select Distinct(zip),id,name group by zip;
Is there any problem if I use as this below?
select distinct zip,name,id from student;
select id, name, distinct(zip) from student;