我有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
答案 0 :(得分:2)
不是很难:)
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