SQL query retrieving first two rows.?
-
I have two tables company and contacts in SQL. A company has c_id as primary key which is a foreign key in contacts. How can i design a query by which i can retrieve the first two contacts of every company in SQL?
-
Answer:
Some ways to do it: http://www.sql-ex.ru/help/select16.php
Serge M at Yahoo! Answers Visit the source
Other answers
Most databases have a way to do something like this, but it's not very standardized. For instance, in MySQL, to get the first two contacts for company #17, you'd do something like: SELECT * FROM `contacts` WHERE `c_id` = 17 LIMIT 0, 2 But in DB2 it'd be: SELECT * FROM CONTACTS WHERE C_ID = 17 FETCH FIRST 2 ROWS ONLY
Silent
select c_id "company_id" , ( select contactid from contacts where contacts.c_id = company.c_id and rownum < 2) "First contact Id", ( select contactid from contacts where contacts.c_id = company.c_id and rownum < 3 and contactid != (select contactid from contacts where contacts.c_id = company.c_id and rownum < 2) ) "Second Contact Id" from company ; the above inner query logic will help you
ananthnag
easy. do a loop command and terminate after the second read of contacts.
Mars
Related Q & A:
- How can I optimize this dynamic SQL query in oracle with PL/SQL?Best solution by docs.oracle.com
- How to convert sql query to Hibernate Criteria query?Best solution by Stack Overflow
- How to convert my SQL query to MS Access query?Best solution by Stack Overflow
- How to make only ONE Sql query?Best solution by Stack Overflow
- How to convert SQL query to LINQ query?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.