选择一个组,其中一个是主要,例如5
分支。因此,地点总数为6
。在每个6
中,搜索3
工作人员job_types LIKE "%C%"
。如果在其中一个6
个地方,3
名工作人员具有给定参数,则查询必须获得所有6
个地点的结果。
澄清: 3
工作人员必须在同一主干/分支机构工作。
因为项目本身非常困难,所以使用 RAW 查询获得结果会更好:
商家信息表
id | mainorbranch | name
--------------------------------------
1 Main Apple
2 Branch Apple London
3 Branch Apple Manchester
4 Main IBM
5 Branch IBM London
etc ...
关系
business_branches表
b_id | branch_id | id
--------------------------------------
1 1 1
2 2 1
3 3 1
4 4 4
5 5 4
// etc
people_details表
d_id | id | job_types
--------------------------------------
1 1 C
2 3 D
3 2 F
4 4 C
5 5 C
// etc
people_branches表
pb_id | branch_id | id
--------------------------------------
1 1 3
2 3 2
3 4 4
4 2 5
5 1 1
// etc
我需要得到什么:
Business id | Name | Postcode
-----------------------------------------
1 Apple postcode
2 Apple 232 postcode
3 Apple 323 postcode
// etc...
帮助程序的数据库结构 http://sqlfiddle.com/#!9/206733
Simplified, minified SQL file with total of 110k+ rows
更新
通过 @KikiTheOne 回答有点工作,但它只获得了一半的结果。另一半失踪了。
答案 0 :(得分:3)
正如聊天中所讨论的那样。这是一个解决方案:
如果你需要公司信息......就像postcode
那样得到@ t1.XXXX。
我改变了
"pb_id" "branch_id" "id"
"1" "1" "3"
"2" "3" "2"
"3" "1" "4"
"4" "1" "5"
"5" "1" "1"
所以我在1个分支中得到3个人
SELECT
t1.id as "Business id",
t1.name as Name,
'postcode' as "Postcode"
FROM SO_business as t1 inner join
(
SELECT * FROM SO_busness_branches as t3
inner join
(
SELECT
t5.branch_id as inner_branch,
count(t5.branch_id) as workers_in,
max(t6.job_types) as job_types,
max(t7.id) as mainbranch
FROM
SO_people_branches as t5
inner join SO_people_details as t6
on t5.id = t6.id
inner join SO_busness_branches as t7
on t5.branch_id = t7.branch_id
WHERE
t6.job_types LIKE '%C%'
GROUP BY
t5.branch_id
) as t4
on t3.id = t4.inner_branch
WHERE t4.workers_in >= 3
) as t2
on t1.id = t2.branch_id
说明:
- 。1最内层SQL计数所有分支与工人(工作人员数量初始化)和Job_type =%c%并加入分支的主要ID。
- .2第二个SQL获取该信息,并且仅选择所有具有worker> = 3
的分支- 。3外部SQL选择所有内部INFOS,并从Inner SQL返回所有branches / main和branchID-Main。 AND将它们连接到Business表,这样你就可以显示所有信息,如那里的信息码
答案 1 :(得分:1)
希望这可行,因为解释与问题中列的名称的关系并不容易。
使用此脚本,您可以添加任何一组main / branch来搜索
SELECT b.id, b.name, 'postcode' as postcode
FROM business b
INNER JOIN business_branches bb ON (bb.branch_id = b.id)
WHERE bb.id IN (
SELECT bb1.id FROM people_details pd
INNER JOIN people_branches pb ON (pb.id = pd.id)
INNER JOIN business_branches bb1 ON (bb1.branch_id = pb.branch_id)
INNER JOIN business b1 ON (b1.id = bb1.branch_id)
WHERE
pd.job_types like '%C%' AND
bb1.id IN (1,4) -- You can add as many group of businesses (main/branch combinations) using the main branch key
GROUP BY pb.branch_id HAVING count(pb.branch_id) >= 3
)