Neo4j 和 Mysql 查询基本语法的区别

每种数据库都有自己的一套查询语言或者标准,即使是同为关系型数据库的Oracle、Sql Server 和 MySQL,其在一些语法细节上也有差异,更别说 Mongo, Redis 类似的非关系型数据库了。Neo4j 也一样,有自己专属的查询语言 Cypher。深入学习其实发现 Neo4j 的查询语法并不难去学习,因为 Cypher 的语意确实简洁,直观。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
-- 1. 全表扫描 --
-- mysql --
SELECT p.*
FROM products as p;
-- neo4j --
MATCH (p:Product)
RETURN p;
-- 2. 查询价格最贵的10个商品,只返回商品名字和单价 --
-- mysql --
SELECT p.ProductName, p.UnitPrice
FROM products as p
ORDER BY p.UnitPrice DESC
LIMIT 10;
-- neo4j --
MATCH (p:Product)
RETURN p.productName, p.unitPrice
ORDER BY p.unitPrice DESC
LIMIT 10;
-- 3. 按照商品名字筛选 --
-- mysql --
SELECT p.ProductName, p.UnitPrice
FROM products AS p
WHERE p.ProductName = 'Chocolade';
-- neo4j --
MATCH (p:Product)
WHERE p.productName = "Chocolade"
RETURN p.productName, p.unitPrice;
-- 其他的写法 --
MATCH (p:Product {productName:"Chocolade"})
RETURN p.productName, p.unitPrice;
-- 4. 按照商品名字筛选2 --
-- mysql --
SELECT p.ProductName, p.UnitPrice
FROM products as p
WHERE p.ProductName IN ('Chocolade','Chai');
-- neo4j --
MATCH (p:Product)
WHERE p.productName IN ['Chocolade','Chai']
RETURN p.productName, p.unitPrice;
-- 5. 模糊查询和数值过滤 --
-- mysql --
SELECT p.ProductName, p.UnitPrice
FROM products AS p
WHERE p.ProductName LIKE 'C%' AND p.UnitPrice 100;
-- neo4j --
MATCH (p:Product)
WHERE p.productName STARTS WITH "C" AND p.unitPrice 100
RETURN p.productName, p.unitPrice;
-- 6. 多表联合查询--
-- mysql --
SELECT DISTINCT c.CompanyName
FROM customers AS c
JOIN orders AS o ON (c.CustomerID = o.CustomerID)
JOIN order_details AS od ON (o.OrderID = od.OrderID)
JOIN products AS p ON (od.ProductID = p.ProductID)
WHERE p.ProductName = 'Chocolade';
-- neo4j --
MATCH (p:Product {productName:"Chocolade"})<-[:PRODUCT]-(:Order)<-[:PURCHASED]-(c:Customer)
RETURN distinct c.companyName;
-- 7. 分组查询 --
-- mysql --
SELECT e.EmployeeID, count(*) AS Count
FROM Employee AS e
JOIN Order AS o ON (o.EmployeeID = e.EmployeeID)
GROUP BY e.EmployeeID
ORDER BY Count DESC LIMIT 10;
-- neo4j --
MATCH (:Order)<-[:SOLD]-(e:Employee)
RETURN e.name, count(*) AS cnt
ORDER BY cnt DESC LIMIT 10
o(╯□╰)o我只要一毛钱的鼓励~~