我正在创建一个产品页面,买家只能从附近的商店根据卖家商店坐标和买家坐标订购。一切都很好,除了搜索功能,当我搜索产品时,它会显示数据库中存储的所有项目,但我不想这样,我还想使用mysql的搜索查询距离。
在mysql中,我使用union搜索卖家和产品。我的问题是如何实现这两个mysql UNION, INNER JOIN
以及 DISTANCE
一起。下面是我的表格结构。
产品
id | podkey | price | name | store_key | owner_pkey | pod_status
-----|---------|--------|----------|------------|-------------|------------
1 | 1ab2 | 100 | Dog | sk76n | MBYUU00 | 1
2 | 0kb2 | 180 | Cat | sk76n | MBYUU00 | 1
3 | 5ab1 | 101 | Doggy | sk76n | MBYUU00 | 1
4 | maf1 | 60 | Bird | sk16b | MBYUU00 | 1
5 | baf0 | 90 | Dog | sk78x | KLYUP07 | 1
商店
id | skey | ownerkey | lat | lng | name
----|-------|----------|------------|------------|-----------------
1 | sk76n | MBYUU00 | 2.922597 | 101.661896 | Cyberjaya store
2 | sk16b | MBYUU00 | 3.7384847 | 107.893837 | Puchong store
3 | sk78x | KLYUP07 | 7.64874646 | 883.893839 | My only store
业主
id | name | owner_key
----|---------|--------------
1 | peter | MBYUU00
2 | john | KLYUP07
下面这是什么是我目前正在使用的显示页面上的项目,并正在工作
SELECT p.id, p.podkey, p.price, p.name, p.store_key, p.pod_status, s.id, s.skey, s.ownerkey, s.name, o.id, o.name, o.owner_key,
SQRT(POW(69.1 * (s.lat - :getBuyerLat), 2) + POW(69.1 * (:getBuyerLon - s.lng) * COS(s.lat / 57.3), 2)) AS distance
FROM product p
INNER JOIN Owners o
ON p.owner_pkey = o.owner_key
INNER JOIN store s
ON s.skey = p.store_key
WHERE p.pod_status = 1
HAVING distance <= 5
下面的查询是我在搜索中尝试的,但它没有返回任何内容或显示任何错误
SELECT * FROM (
SELECT 'products' as type, pod_status AS stat, name AS name, price AS price, store_key AS skey, NULL AS distance FROM product p
UNION
SELECT 'sellers' as type, 1 AS stat, name AS name, NULL AS price, NULL AS skey, NULL AS distance FROM Owners o
UNION
SELECT 'outlets' as type, 1 AS stat, name AS name, NULL AS price, skey AS skey,
SQRT(POW(69.1 * (s.lat - :getBuyerLat), 2) + POW(69.1 * (:getBuyerLon - s.lng) * COS(s.lat / 57.3), 2)) AS distance
FROM store s
) sfoo
INNER JOIN store sj
ON sj.skey = sfoo.store_key
WHERE sfoo.name LIKE %dog% AND sfoo.stat = 1 HAVING distance <= 5
有人能帮我吗?我是麦克维http://sqlfiddle.com/#!9/AF39/2/0号
1条答案
按热度按时间xiozqbni1#
我不知道为什么这让人困惑。子查询只返回outlets,因为
distance
是NULL
另外两个。没有一家商店的名字里有“狗”。看起来很简单。第一个查询与第二个查询无关,因为过滤条件不同。