简体   繁体   English

正确的复杂MySQL查询联接表

[英]Complex MySQL query joining tables correctly

I have 3 tables that are inter-related and I'm trying to query the data correctly so that I get everything that I need. 我有3个相互关联的表,我试图正确地查询数据,以便获得所需的一切。

Here are the 3 tables that I have: 这是我拥有的3张桌子:

order_items order_items

+------------+--------------+------+-----+
| order_id   | product_id   |count | max |
+------------+--------------+------+-----+
| 1AB45      | 3214         | 1    | 20  |
| YE72H      | 314          | 2    | 20  |
| HWYE1      | 5311         | 3    | 10  |
| HWYE1      | 314          | 1    | 20  | 
+------------+--------------+------+-----+

orders 命令

+-----------+-------------+---------+-----+
| order_id  | buyer_email | user_id | ... |
+-----------+-------------+---------+-----+
|  1AB45    | user1@gmail | 123     |     |
|  YE72H    | user2@al.uk | 124     |     |
|  HWYE1    | me@mail.com | 125     |     |
+-----------+-------------+---------+-----+

reg_keys reg_keys

+-----------+-------------+---------+------------+
| reg_key   | time_redeem | user_id | product_id |
+-----------+-------------+---------+------------+
|  UN-12XZ  | 2015-11-12  | 123     |    3214    |
|  UN-34AB  | 2015-10-12  | 125     |    5311    |
|  UN-67UY  | 2015-09-12  | 125     |    314     |
+-----------+-------------+---------+------------+

I am looking to get all of the registration keys where the count/quanity is equal to 1 and time_redeemed is not NULL. 我正在寻找所有计数/数量等于1并且time_redeemed不为NULL的注册键。 Here's my query which is getting results but overwrites all of the other order info with the same email/order_id: 这是我的查询,正在获取结果,但是使用相同的email / order_id覆盖了所有其他订单信息:

SELECT * FROM order_items
JOIN orders ON orders.order_id = order_items.order_id
JOIN reg_keys ON reg_keys.user_id=orders.user_id and reg_keys.product_id=order_items.product_id
WHERE count=1 and reg_keys.redeemed_by is not null
GROUP BY reg_key ORDER BY time_redeem DESC

This is yielding me no results. 这没有结果。 What have I messed up? 我搞砸了什么?

Don't use group by and select the key column 不要使用分组依据并选择键列

SELECT 
    reg_keys.reg_key * 
FROM 
    order_items
JOIN 
    orders ON orders.order_id = order_items.order_id
JOIN 
    reg_keys ON reg_keys.user_id = orders.user_id 
             AND reg_keys.product_id = order_items.product_id
WHERE 
    count = 1 
    AND reg_keys.redeemed_by IS NOT NULL
ORDER BY time_redeem DESC;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM