简体   繁体   English

SQL:如何将联合全部分离到单独的列中?

[英]SQL: How do I separate Union all into separate columns?

new user.新用户。 So I'm making an SQL database project themed around an escape room/restaurant and I have two separate tables, one called ingredients and another called assets.所以我正在制作一个以逃生室/餐厅为主题的 SQL 数据库项目,我有两个单独的表,一个称为成分,另一个称为资产。 Below is an example of the Ingredients Table以下是成分表的示例

| ingredients_id | ingredients_name | ingredients_cost | ingredient_stock | ingredient_availability
| 1              | Beef Burger      | 1.99             | 12               | 1 
| 2              | Cheese           | 1.99             | 0                | 0
| 3              | Bacon            | 1.99             | 43               | 1

and this is an example of the assets table这是资产表的一个例子

| asset_id | asset_name | asset_status | asset_availability
| 1        | escape_1   | Clean        | 1          
| 2        | escape_2   | Clean        | 1
| 3        | escape_3   | Clean        | 1

What I'm trying to do is make a table that combines the both of them called Storage (Already have the table through primary/foreign key), here's what I want it to appear as:我想要做的是制作一个将它们组合在一起的表,称为存储(已经通过主键/外键获得了表),这就是我希望它显示的内容:

| Name        | Stock (Ingredients Only) | Availability
| escape_1    | NULL                     | TRUE
| escape_2    | NULL                     | TRUE
| escape_3    | NULL                     | TRUE
| Beef Burger | 12                       | TRUE
| Cheese      | 0                        | FALSE
| Bacon       | 43                       | TRUE

Here's my SQL code so far:到目前为止,这是我的 SQL 代码:

SELECT asset_name AS "Name" FROM escaperoom_assets 
UNION ALL 
SELECT ingredients_name FROM ingredients

I'm able to put the ingredient and asset names into one list but I can't make a separate column for the others.我可以将成分和资产名称放入一个列表中,但我无法为其他列表创建单独的列。 Essentially I want it so that it'll display a list of all the assets and ingredients in one column, check how much is in stock for the other (only for the ingredients table), and if they are available or not (identified as True/False or 0 or 1).本质上我想要它,以便它将在一个列中显示所有资产和成分的列表,检查另一列的库存量(仅针对成分表),以及它们是否可用(标识为 True /False 或 0 或 1)。

Just add the columns you want in each subquery:只需在每个子查询中添加您想要的列:

SELECT asset_name AS Name, NULL as stock, asset_availabilty as availability
FROM escaperoom_assets 
UNION ALL 
SELECT ingredients_name, ingredient_stock, ingredient_availability
FROM ingredients;

I'm not sure why you want to convert 0/1 to true/false.我不确定您为什么要将 0/1 转换为真/假。 The numbers seem fine, but you can use conditional logic to convert them to strings if you want.数字看起来不错,但如果需要,您可以使用条件逻辑将它们转换为字符串。

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

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