简体   繁体   English

无法编写涉及来自三个表的有序数据的MySQL查询

[英]Trouble writing MySQL query involving ordered data from three tables

I have a table called tags , like this: 我有一个称为tags的表,如下所示:

+-------+----------+
| tagID | tagName  |
+-------+----------+
|     1 | jewelery |
|     2 | gifts    |
|     3 | asdf     |
|     4 | fashion  |
|     5 | diamonds |
+-------+----------+

Then a table called coupon_tags , like this: 然后是一个名为coupon_tags的表,如下所示:

+-------+----------+
| tagID | couponID |
+-------+----------+
|     1 |        1 |
|     2 |        1 |
|     3 |        2 |
|     4 |        2 |
|     5 |        3 |
+-------+----------+

And lastly, a table called coupons , here are the pertinent parts (id is the same as couponID elsewhere): 最后,一个名为coupons的表,这是相关的部分(id与其他地方的couponID相同):

+----+-----------------+
| id | zone            |
+----+-----------------+
|  1 | Los Angeles     |
|  2 | Orange County   |
|  3 | Los Angeles     |
|  5 | Orange County   |
|  6 | Orange County   |
+----+-----------------+

What I need to write a query for: I want to get tagNames via the first table that correspond to the ordered list of the top 10 most used tagIDs in the second table, but it only looks through couponIDs that match another criteria - that the "zone" be a certain zone. 我需要编写查询的内容:我想通过第一个表获取与第二个表中前10个最常用的tagID的有序列表相对应的tagName,但它只会通过匹配其他条件的couponID来查找-区域”是某个区域。 In the end, only the top 10 tagNames from a certain zone will show. 最后,将仅显示某个区域中的前10个tagName。 I've never done a triple-table query before, any help? 我以前从未做过三表查询,有什么帮助吗?

I'm trying to keep this purely SQL, as I had a partially working PHP solution but it was messy and very slow. 我试图保留此纯SQL,因为我有一个可以部分使用的PHP解决方案,但是它很杂乱且非常缓慢。

SELECT tags.tagName FROM
(SELECT tagID, COUNT(*) FROM
 coupon_tags 
 JOIN coupons ON coupons.couponID = coupon_tags.couponID AND zone = 'Los Angeles' 
 GROUP BY tagID ORDER BY COUNT(*) DESC LIMIT 10) AS most_used
JOIN tags ON most_used.tagID = tags.tagID 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM