简体   繁体   中英

MySQL query to select distinct values from one table and all values from a separate table

I have two tables for surveys. Table 1 contains the surveys that are sent out with the following fields: SID,SalesRep,Location. Table 2 contains the survey results that are returned with the following fields: RID,SID,QID,AID.

In table 1, SID is unique, and there are no duplicates. In Table 2, RID is unique, and represents each question that is answered, and the answer. The SID in Table 2 represents the survey from which the questions have been answered. So, if there were 10 questions answered on the survey, there would be 10 rows in Table 2 with the same SID.

What I need to do is find out how many surveys have been sent and how many taken for each sales person. I can use two queries to find the information separately:

  1. SELECT * FROM Table1
  2. SELECT DISTINCT Table2.SID, Table1.SalesRep,Table1.Location FROM Table2 INNER JOIN Table1 on Table1.SID = Table2.SID

What I would like to do is have ONE query that will give me both results. I'm assuming it would take some kind of OUTER JOIN since there will be more results from Table1 than Table2 because we don't get 100% return on the surveys. However, when I try to run an OUTER JOIN, it locks up and returns nothing. These tables aren't very large at this point.

Can someone please point me in the right direction? Is this even possible?

You have't specified well enough about your result but as I could understand,You may try this hope it works
SELECT * FROM Table1
WHERE SID IN (SELECT DISTINCT SID FROM Table2)

If it doesn't works please specify well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM