SQL作业求助:如何关联varchar与integer实现表连接?
Hey there! Let's work through this problem together. The error you're seeing happens because your order_items (either a comma-separated string or a character varying array) can't directly match the integer menu_items_number in the menu table—we need to break down the order items, convert their type properly, then map them to the menu names before putting everything back together.
Step-by-Step Breakdown
- Split the order items: First, we need to turn the grouped order item numbers into individual rows. If
order_itemsis a comma-separated string (like'1,1,2,3'), useSTRING_TO_ARRAYto convert it into an array, thenUNNESTto split that array into separate rows. If it's already acharacter varying[]array, skip theSTRING_TO_ARRAYstep and just useUNNEST. - Fix type mismatch: Convert each split item number from text to an integer so it can match the
menu_items_number(which is an integer type). - Map to menu names: Join the split items with the menu table to get the corresponding dish names.
- Reassemble the order: Group the results by
order_numberand useSTRING_AGGto concatenate the dish names back into a single comma-separated string.
Working SQL Query
If order_items is a comma-separated string:
SELECT o.order_number, STRING_AGG(m.menu_item, ', ') AS order_item_names FROM d.orders o CROSS JOIN UNNEST(STRING_TO_ARRAY(o.order_items, ',')) AS item_num JOIN d.menu m ON CAST(item_num AS INTEGER) = m.menu_items_number GROUP BY o.order_number;
If order_items is already a character varying[] array:
SELECT o.order_number, STRING_AGG(m.menu_item, ', ') AS order_item_names FROM d.orders o CROSS JOIN UNNEST(o.order_items) AS item_num JOIN d.menu m ON CAST(item_num AS INTEGER) = m.menu_items_number GROUP BY o.order_number;
Example Output
For an order with order_number = 101 and order_items = '1,1,2,3', this query will return:
101 | hamburger, hamburger, fries, drink
This should resolve the type mismatch error and give you the exact output you're looking for!
内容的提问来源于stack exchange,提问作者fire2018

