开发者

Joining unrelated tables

I am working in SQL Server 2005. I have a table that lists stores and a separate table that lists departments. There is no key relationships between the tables. My goal is create a query that lists each department for each store. Ideally the results will be:

store  department

1        candy

1        ice

1 &nb开发者_如何转开发sp;      drinks

2        candy

2        ice

2        drinks


You can do the above query with a cross join (with no relationships in the WHERE clause)

SELECT d.department, s.store FROM departments d
CROSS JOIN stores s


If all stores have all departments, then you might try a CROSS JOIN

SELECT store, department
FROM stores
CROSS JOIN departments


Like this: http://ideone.com/KErj3

Use JOIN. (The syntax will be a bit different for the creation of the tables since Ideone is SQLite, though.)


You can use JOIN too

SELECT s.store, d.department
FROM stores s
JOIN departments d
  ON 1=1


Is this the same as a cartesian?

SELECT s.store, d.department
FROM stores s, departments d
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜