| SQL - Questions and Answers Have a SQL question? Post it here. First do a search to see if someone hasn't already answered it. |
|
|||
Most Basic SQL QuestionHi, Am starting to teach myself SQL. I cannot figure out how to do the most simple of queries, and it is driving me nuts. Here's the basic scenario:
Table: Customer custid firstname lastname Table: Transactions custid transdate transamount I want a query which will display ALL customers and any associated transactions. However, the query I used (below) only returns the customer if there is a transaction for it. For customers with no transactions, they are not being listed and I need help to show me how to structure the query to that the listing of the master table is not dependent on there being any child records in existence. select customer.custid, customer.firstname, customer.lastname, transactions.transdate, transactions.transamount from customer, transactions where customer.custid=transactions.custid Please tell me where I am going wrong!!! |
|
|||
|
Try a JOIN, specifically a LEFT [OUTER] JOIN (the OUTER keyword is optional). This will return all records in the left table (Customer), including those that have no transactions, along with records in the right table (Transactions) that match a record in the left table (which sounds like all the records in this case). Here's the syntax:
select customer.custid, customer.firstname, customer.lastname, transactions.transdate, transactions.transamount from customer LEFT JOIN transactions ON customer.custid=transactions.custid Note that in the records for customers that don't have a transaction, you'll get NULL for all the fields from the Transactions table. |
![]() |
| Thread Tools | Search this Thread |
|
|