我是SQL的新手,希望获得查询帮助。
我有以下表格:
#product
------------------------------------------
| product_id | title | date | price | lang |
------------------------------------------
#product_to_categories
-------------------------------
| id | category_id | product_id |
-------------------------------
#category
--------------------
| category_id | name |
--------------------
我想选择所有具有特定类别且属于特定类别的产品。
是否有办法在一个请求中执行,或者我是否应首先选择具有特定lang的所有产品,然后如果它们位于产品类别表中,则逐个查看?
答案 0 :(得分:2)
SELECT dbo.product.lang, dbo.product.product_id, dbo.product.title, dbo.product.date, dbo.product.prize, dbo.category.category_id AS Expr1
FROM dbo.product_to_categories INNER JOIN
dbo.product ON dbo.product_to_categories.product_id = dbo.product.product_id INNER JOIN
dbo.category ON dbo.product_to_categories.category_id = dbo.category.category_id
WHERE (dbo.product.lang = N'desiredang') AND (dbo.category.category_id = 'desired category id')
答案 1 :(得分:2)
请参阅此SQLFiddle中的交互式示例:
SELECT
p.title,
c.name as category
FROM product p
INNER JOIN product_to_categories pc on pc.product_id = p.product_id
INNER JOIN category c on c.category_id = pc.category_id
WHERE p.lang='en' and c.category_id in (3, 4)
结果示例如下:
---------------
title | name
---------------
Apple | Green
Apple | Red
Kiwi | Green
如果要对内容进行分组,postgres
(自9.0起)有built in function string_agg
,如果您按如下方式操作脚本,则可以使用SELECT
p.title,
string_agg(c.name, ', ') as category
FROM product p
INNER JOIN product_to_categories pc on pc.product_id = p.product_id
INNER JOIN category c on c.category_id = pc.category_id
WHERE p.lang='en' and c.category_id in (1, 3)
GROUP BY p.product_id, p.title
ORDER BY p.title
:
---------------
title | name
---------------
Apple | Red, Green
Kiwi | Green
请参阅此SQLFiddle中的交互式示例。
结果示例如下:
class Person {
var name = String()
}
当您了解如何与结果集进行交互时,了解SQL连接会更简单。这是一个great reference。 图片由halfgaar的这篇文章引用。