Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query for Selecting Multiple Records

Tags:

sql

mysql

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?
like image 519
user823911 Avatar asked Feb 07 '12 18:02

user823911


People also ask

How do I select multiple data in SQL?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

How do I select multiple rows in SQL?

Syntax - SELECT column1,column2, …, columnN FROM table_name; column1,column2 – Specifies the name of the columns used to fetch. table_name - Specifies the name of the table.

How do I select multiple values in one column in SQL?

Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);


3 Answers

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
like image 147
TheBoyan Avatar answered Oct 16 '22 16:10

TheBoyan


You can try this
SELECT * FROM Buses WHERE BusID in (1,2,3,4,...)

like image 42
Kamran Ali Avatar answered Oct 16 '22 17:10

Kamran Ali


You're looking for the IN() clause:

SELECT * FROM `Buses` WHERE `BusID` IN (1,2,3,5,7,9,11,44,88,etc...);
like image 41
Michael Berkowski Avatar answered Oct 16 '22 15:10

Michael Berkowski