用于连接表的SQL查询

时间:2013-04-30 07:41:21

标签: sql

我有四个表,想要创建一个每个客户端只有行的新表。

客户端

id  |   fname  |   lname   |   city  |  company_id

1   |   kim    |   smith   |   jhb   |  1
2   |   tom    |   jones   |   ct    |  1
3   |   john   |   short   |   pe    |  2

CLIENT_DIVISION

id   |  client_id  |  division_id

1    |  1          |  1
2    |  1          |  2
3    |  2          |  1
4    |  2          |  3
5    |  2          |  4
6    |  3          |  4
7    |  3          |  2

DIVISION

id  |  name

1   |  estate
2   |  property
3   |  litigation
4   |  commercial

COMPANY

id  | name

1   | compA
2   | compB
查询divisions = estate

时,

DESIRED TABLE RESULT

id  |  fname  | lname  | city  |  company_name

1   |  kim    | smith  | jhb   |  compA
2   |  tom    | jones  | ct    |  compA

我希望能够为每个客户端创建一个新表,其中将除法参数传递给查询。传递的参数将来自用户在提交查询之前选择的复选框。如何为其创建连接查询?

1 个答案:

答案 0 :(得分:0)

我希望此查询能为您提供帮助:

SELECT DISTINCT     CLIENT.id, CLIENT.fname, CLIENT.lname, CLIENT.city, COMPANY.name
FROM         CLIENT INNER JOIN
                  CLIENT_DIVISION ON CLIENT.id = CLIENT_DIVISION.client_id INNER JOIN
                  COMPANY ON CLIENT.company_id = COMPANY.id INNER JOIN
                  DIVISION ON CLIENT_DIVISION.division_id = DIVISION.id
WHERE     (DIVISION.id = @division_id)

您需要将@division_id替换为您的值。