繁体   English   中英

MySQL从联接表返回多行作为列

[英]MySQL return multiple rows from joined table as columns

我有2张桌子(商店和营业时间)。

我希望将商店的营业时间作为栏而不是单独的行来返回。 我在Stack上看到了一些想法,但没有一个可以转变为我自己的情况。

Stores
------
id
name

Opening Hours
-------------
store_id
dayofweek
openinghh
openingmm
closinghh
closingmm

每个商店在“营业时间”表中都有7个条目(一周中的每一天一个)

返回的行将是

store_id | name | Monday Opening | Monday Closing |Tues Opening | Tues Closing etc

不太难:)

SELECT s.id as store_id
, s.name as store_name
##
, concat(oh_mon.openinghh, ':', oh_mon.openingmm) as monday_opening
, concat(oh_mon.closeinghh, ':', oh_mon.closeingmm) as monday_closing
##
, concat(oh_tue.openinghh, ':', oh_tue.openingmm) as tuesday_opening
, concat(oh_tue.closeinghh, ':', oh_tue.closeingmm) as tuesday_closing
##
, concat(oh_wed.openinghh, ':', oh_wed.openingmm) as wednesday_opening
, concat(oh_wed.closeinghh, ':', oh_wed.closeingmm) as wednesday_closing
##
FROM stores s
##
LEFT JOIN opening_hours oh_mon
ON oh_mon.store_id = s.id
AND oh_mon.dayofweek = 'Monday'
##
LEFT JOIN opening_hours oh_tue
ON oh_tue.store_id = s.id
AND oh_tue.dayofweek = 'Tuesday'
##
LEFT JOIN opening_hours oh_wed
ON oh_wed.store_id = s.id
AND oh_wed.dayofweek = 'Wednesday'
##
WHERE 1=1

并在要显示的每一天使用LEFT JOIN

暂无
暂无

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

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