SQL:如何从两个表中获取关系数据? (使用JOIN?)

时间:2013-10-28 20:14:50

标签: mysql sql join

我一直在尝试做一些跨关系的SQL查询,到目前为止没有成功。想知道是否有人可以提供帮助?

我有两张感兴趣的表格,并且我试图找出哪些客户(=公司联系人1)必须做出未完成的项目。这是表结构:

TABLE: CUSTOMERS

ID    |    CUSTOMER_NAME    |    COMPANY_CONTACT
=================================================
1           Bob                     1
2           Billy                   2
3           Susan                   2
4           Ryan                    3
5           Sally                   1

TABLE: TO_DOS
ID    |    TASK         |    CUSTOMER_ID
============================================
1          Make Tea                 5
2          Pick flowers             1
3          Do invoices              3
4          Tidy up                  4
5          Drive van                2

理想的输出是

CUSTOMER_ID     |   CUSTOMER_NAME  |  TASK
=================================================================
5           Sally         Make Tea
1           Bob           Pick flowers

到目前为止,我已经尝试过了,但它并没有让我到处都是:

SELECT * FROM TO_DOS
INNER JOIN CUSTOMERS
WHERE CUSTOMERS.COMPANY_CONTACT=1

任何想法都非常感谢!

2 个答案:

答案 0 :(得分:4)

SELECT CUSTOMERS.ID, CUSTOMERS.CUSTOMER_NAME, TO-DOS.TASK 
FROM TO_DOS
INNER JOIN CUSTOMERS 
ON TO_DOS.CUSTOMER_ID = CUSTOMERS.ID
WHERE CUSTOMERS.COMPANY_CONTACT = 1

答案 1 :(得分:2)

SELECT * FROM TO_DOS AS A
INNER JOIN CUSTOMERS AS B ON A.CUSTOMER_ID=B.ID
WHERE CUSTOMERS.COMPANY_CONTACT=1

公司联系电话号码将决定选择哪个客户,因此如果您想选择Sally和Bob,您可以选择1。