简体   繁体   English

带有两个单独联接的MySQL查询

[英]Mysql Query with two seperate join

Does anyone know the solution to this problem ? 有谁知道解决这个问题的办法? There are 3 Tables: orders , order_groups and stores . 有3个表: ordersorder_groupsstores
I want to list the orders, with the names of the stores where the order was placed, and where the order is going to be delivered. 我想列出订单,以及下订单的商店名称以及要下达订单的商店的名称。

I keep the from_store_id , and to_store_id in the order_groups table 我将from_store_idto_store_idorder_groups表中

Listing these orders would be simple, i just left join the order_groups to orders , and select the name, from_shop_id and to_shop_id , but the problem is i want the name of the stores not the id, and the store names are placed in a different table (stores) 列出这些订单很简单,我只剩下将order_groups加入orders ,然后选择名称from_shop_idto_shop_id ,但是问题是我想要商店的名称而不是ID,并且商店名称被放置在另一个表中(店)

Here is what im talking about: 我在说什么:

Table orders
id  group_id    name            madeup_id
1     11        johnny cash         1
2     12        billy bob           1
LEFT JOIN order_groups on order_groups.id = orders.group_id
Table order_groups
id   from_store_id   to_store_id
11     55               56
12     56               55
Table stores
id    store_name
55     thisstore
56     thatstore
The result im looking for is:
   name         from_store   to_store
1.johhny cash   thisstore, thatstore
2.billy bob     thatstore, thisstore

The statement i have yet: 我尚未发表的声明:

SELECT 
orders.name, something as from_store, something as to_store
FROM orders
LEFT JOIN order_groups on order_groups.id = orders.group_id

somehow join stores on the order_groups.from_store_id = stores.id

WHERE orders.madeup_id = 1

Any idea how to select and join the store names to the query ? 知道如何选择商店名称并将其加入查询吗?

One more question. 还有一个问题。 I actually want to list two kind of orders in one query from different tables too, im on the right track with this structure ? 我实际上也想在一个查询中列出来自不同表的两种订单,即时消息在这种结构的正确轨道上?

SELECT a,b FROM a LEFT JOIN b ON b.something=a.something WHERE something 
UNION ALL
SELECT a,b FROM c LEFT JOIN c ON c.something=a.something WHERE something

You only need to join 2 times the same table! 您只需要加入2次同一张桌子!

SELECT 
orders.name, fromStore.store_name as from_store, toStore.store_name as to_store
FROM orders
LEFT JOIN order_groups on order_groups.id = orders.group_id
left join stores fromStore on the order_groups.from_store_id = fromStore.id
left join stores toStore on the order_groups.to_store_id = toStore.id
WHERE orders.madeup_id = 1

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

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