查询有两个选择和连接

时间:2015-04-20 22:58:58

标签: mysql join

需要帮助形成具有两个带连接选择的查询。我在相同的信息中搜索重复的条目,但信息位于两个表中。

表ordermeta有orderid和formid。 表订单有orderid和userid

我将订单加入订单两次,然后搜索formid和userid匹配的不同订单。

以下是我的尝试:

SELECT om0.orderid AS order1, om1.orderid AS order2
FROM ordermeta om0
LEFT JOIN ordermeta om1 ON om0.formid = om0.formid
LEFT JOIN orders o0 ON om0.orderid = o0.orderid
LEFT JOIN orders o1 ON om1.orderid = o1.orderid
WHERE o0.userid = o1.userid
AND om0.orderid != om1.orderid

我也尝试了这个但是彻底混淆了并转移到上面的代码:

SELECT order1.oid1, order1.pd1, order2.oid2, order2.pd2
FROM (
    SELECT o1.orderid AS oid1, paid AS pd1, uid AS uid1, fid AS fid1 
    FROM  `orders` o1
    JOIN ordermeta om1 ON o1.orderid = om1.orderid
) order1
JOIN (
    SELECT o2.orderid AS oid2, paid AS pd2, uid AS uid2, fid AS fid2 
    FROM  `orders` o2
    JOIN ordermeta om2 ON o2.orderid = om2.orderid
) order2 ON order1.uid1 = order2.uid2 AND order1.fid1 = order2.fid2

我得到的结果太多了,而不是我期待的结果。应该是1000的数量级,但是我的数量超过了223000。

示例数据:

ordermeta table
HEADER: omid, orderid, formid, <other data>
1, 101, 201, ...
2, 102, 202, ...
3, 103, 201, ...
4, 108, 201, ...
5, 109, 202, ...

orders table
HEADER: orderid, userid, <other data>
101, 2000, ...
102, 2000, ...
103, 2001, ...
108, 2000, ...
109, 2001, ...

首先,我需要将userid与结合了formid的ordermeta相关联。然后,搜索组合数据中的副本,其中formid = formid和userid = userid,并返回两个ord​​erid。

在上面的示例中,我应该获得orderids 101和108,因为它们的用户ID和formid在加入后是匹配的。

2 个答案:

答案 0 :(得分:1)

你的逻辑非常接近:

select * 
  from ordermeta om1
  inner join
  orders o1
    on om1.orderid = o1.orderid
  inner join
  ordermeta om2
    on om1.formid = om2.formid
  inner join 
  orders o2 
    on om2.orderid = o2.orderid
  where o1.userid = o2.userid
    and o1.orderid <> o2.orderid

演示小提琴:http://sqlfiddle.com/#!9/b0936/1

事实上,如果您没有对两个ordermeta表的连接谓词进行拼写错误,那么您的原始查询就没问了

答案 1 :(得分:1)

您的问题出现在首次加入条件中:

LEFT JOIN ordermeta om1 ON om0.formid = om0.formid

显然是一个错字,但om0.formid = om0.formid总是如此。将其更改为:

LEFT JOIN ordermeta om1 ON om0.formid = om1.formid

你应该将条件int he qhere子句移动到join子句中,所以整个查询看起来像:

SELECT om0.orderid AS order1, om1.orderid AS order2
FROM ordermeta om0
LEFT JOIN ordermeta om1 ON om0.formid = om0.formid
    AND om0.orderid != om1.orderid
LEFT JOIN orders o0 ON om0.orderid = o0.orderid
LEFT JOIN orders o1 ON om1.orderid = o1.orderid 
    AND o0.userid = o1.userid