创建单个查询以从表中获取数据作为单独的行

时间:2015-06-19 07:51:34

标签: mysql sql-server sql-server-2012

我在想是否有更好的方法可以从数据库中查询产品,产品选项和产品选项

我的数据库结构如下:

product table (product_id, product_name)
product_options table (option_id, option_name, product_id)
product_optionChoices (Choice_id, choice_name, Option_id)

我想要一个单独的查询,它会在单独的行中返回所有产品和选项,如:

--------------------------------------------------------------------------------
| product_id | product_name | option_id | option_name | choiceId | choice_name |
| 1          | shoes        |           |             |          |             |
| 1          |              | 1         | choose color|          |             |
|            |              | 1         |             | 1        | red         |
|            |              | 1         |             | 2        | blue        |
--------------------------------------------------------------------------------

现在我正在使用3个sepearte查询获取产品,产品选项和product_optionChoices,并在coldfusion中使用QueryAddRow将查询附加在一起。

由于

2 个答案:

答案 0 :(得分:3)

也许这个解决方案可以帮助你,即使我不喜欢它。
这将完全返回您想要的内容(更新)。

SELECT  p.product_id, p.product_name, '' as option_id, '' as option_name, ''  as choiceId, '' as choice_name FROM `product` p
UNION ALL
SELECT  pr.product_id as product_id, '' as product_name, o.option_id, o.option_name, '' as choiceId, '' as choice_name FROM `product_options` o
INNER JOIN product pr
ON pr.product_id = o.product_id
UNION ALL
SELECT  '' as product_id, '' as product_name, op.option_id as option_id, '' as option_name, c.choice_Id, c.choice_name FROM `product_optionChoices` c
INNER JOIN product_options op
ON op.option_id = c.option_id

答案 1 :(得分:0)

这适用于SQL Server

SELECT P.product_id, P.product_name, PO.option_id, PO.option_name, POC.choiceId, POC.choice_name
FROM product P LEFT OUTER JOIN product_options PO on P.product_id = PO.product_id
               LEFT OUTER JOIN product_optionChoices POC on POC.option_id = PO.Option_id