我有三张桌子:
<a href="http://twitter.com/share?url=http%3A%2F%2Fprotein.rnet.missouri.edu%3A8080%2FPServer%2Fresults.jsp%3Foutput%3D%2BID&text=My Results&hashtags=UMCProteinServer" target="_blank"><img src="http://www.simplesharebuttons.com/images/somacro/twitter.png" alt="Twitter" /></a>
现在我希望在中间表中对“蓝色”记录的“好”或“坏”值的计数超过底部表中“值”字段的值
Master table: top
Fields: id, field1
Details table: middle
Fields: id, top_id, category, selection
The category field can only have two values: red, blue.
The selection field only has two values: good, bad
This table has a reference field (top_id) pointing to the top table
Extra table: bottom
Fields id, middle_id, value (value field can only have values 1, 2)
This table has a reference field (middle_id) only pointing to the records in the middle table whose category value is "red".
从视觉上看,这些记录形成如下树形结构:
1. there are "red" records in the middle table, AND
2. these "red" records point to the same records in the top table as the "blue" records, AND
3. these "red" records have details records in the bottom table and these records have 1 or 2 or 3 in the "value" field.
在我的情况下,我无法使用特定于数据库的解决方案或程序。我希望为此编写一个查询,但未能这样做。
更新
目标结果应该是类似于以下的行:
1(底部“值”字段的值),良好(“蓝色”记录带有“好”值),3(“好”值“蓝色”记录出现三次值“1”)< / p>
感谢您的帮助!
更新2
我相信Misandrist的答案是正确的,但他可能很快写完了。在我的测试之后,我做了更改,以下是完整的工作脚本。
top (top table)-----records in the middle table with category being "blue"
|
|----records in the middle table with category being "red"
|
|-------records in the bottom table
Misandrist,谢谢!
答案 0 :(得分:1)
首先,让我们提出描述关系的查询:
SELECT * FROM top
INNER JOIN middle AS mblue ON mblue.top_id = top.id
INNER JOIN bottom ON bottom.middle_id = mblue.id
由于我们对中间表有多个约束,我们将为它添加另一个连接:
INNER JOIN middle AS mred ON mred.top_id = top.id
接下来,让我们来表达一下约束:
中间表中有“红色”记录:
WHERE mred.category = red
AND这些“红色”记录指向顶部表中与“蓝色”记录相同的记录:
AND mblue.category = blue
AND这些“红色”记录在底部表中有详细记录,这些记录在“值”字段中有1或2或3个:
AND bottom.value in (1, 2, 3)
把它们放在一起:
SELECT *
FROM top
INNER JOIN middle AS mred ON mred.top_id = top.id
INNER JOIN bottom ON bottom.middle_id = mblue.id
INNER JOIN middle AS mblue ON mblue.top_id = top.id
WHERE mred.category = 'red'
AND mblue.category = 'blue'
AND bottom.value in (1, 2, 3)
这些描述了约束的形状。
现在让我们在中间表中获取“蓝色”记录的“好”或“坏”值的计数,而不是底部表格中“value”字段的值:
SELECT bottom.value, mblue.selection, COUNT(mblue.id)
INNER JOIN middle AS mred ON m1.top_id = top.id
INNER JOIN bottom ON bottom.middle_id = mblue.id
INNER JOIN middle AS mblue ON mblue.top_id = top.id
WHERE mred.category = 'red'
AND mblue.category = 'blue'
AND bottom.value in (1, 2, 3)
GROUP BY bottom.value, mblue.selection
请注意,查询的核心结构保持不变,但我们只是替换了SELECT
,并添加了GROUP BY
。