我正在使用3个表,尝试提取符合特定条件的列表。 我需要公司表中的公司列表,这些公司有一个活跃的机会(iactive在机会表中为1)并且在类型订单或订单2的备注表中有记录。
Companies Table
+------+------------------+
| cid | ccyname |
+------+------------------+
| 1c | Bobs Fish |
| 2c | Sheep Counters |
| 3c | Old Timers |
| 4c | Roasted Nuts |
+------+------------------+
Notes Table
+------+--------+--------+
| nid |ntype |cid |
+------+--------+--------+
| 1n | order |3c |
| 2n | quest |1c |
| 3n | order2 |2c |
| 4n | cancel |2c |
+------+--------+--------+
Opportunities Table
+------+--------+--------+
| oid |iactive | cid |
+------+--------+--------+
| 1o | 1 | 1c |
| 2o | 0 | 3c |
| 3o | 1 | 3c |
| 4o | 1 | 2c |
+------+--------+--------+
通过这个例子,结果应该是:
Results
+----------------+--------+
| ccyname | oid |
+----------------+--------+
| Old Timers | 3o |
| Sheep Counters | 4o |
+----------------+--------+
只有那些同时拥有积极机会和订单或订单2的公司才会给我。
我尝试过几种不同的方式,但我总是只得到一个结果或太多结果。我可以得到一些帮助吗?
这是在SQL Server 2005上。
谢谢, 约翰
答案 0 :(得分:1)
SELECT DISTINCT(ccyname), oid
FROM Companies AS c
INNER JOIN Notes AS n ON c.cid = n.cid
INNER JOIN Opportunities AS o ON c.cid = o.cid
WHERE n.ntype IN ('order','order2')
AND o.iactive = 1;
警告:未经测试。
答案 1 :(得分:1)
SELECT
C.ccyname, O.oid
FROM
Companies C
JOIN
Opportunities O AND O.cid = c.cid
WHERE
O.iactive = 1
AND
EXISTS (SELECT * FROM Notes N
WHERE N.ntype IN ('order', 'order2') AND N.cid = c.cid)
答案 2 :(得分:0)
SELECT DISTINCT cid, ccyname
FROM Companies c
INNER JOIN Notes n ON n.cid = c.cid AND n.ntype = 'order2' OR n.ntype = 'order'
INNER JOIN Opportunities o ON o.cid = c.cid AND o.iactive = 1