我有3张桌子:
我需要获取cat slug,并将stats表的unit slug与unit_cat表和unit_list结合在一起。问题是我同时加入了unit_stats.id_unit_1
和unit_stats.id_unit_2
这是结构的sqlfiddle和我当前的查询(未得到所需的结果):
SELECT
unit_stats.hits AS hits,
unit_cat.slug AS cat,
unit_list.slug AS slug_1,
unit_list.slug AS slug_2
FROM unit_stats
JOIN unit_cat ON unit_cat.id_cat = unit_stats.id_cat
JOIN unit_list ON unit_list.id_unit = unit_stats.id_unit_1 AND unit_list.id_unit = unit_stats.id_unit_2
ORDER BY hits DESC
所需结果应采用以下格式:
temperature, celsius, fahrenheit
感谢您的帮助。
答案 0 :(得分:1)
您的查询无效,因为您在JOIN
到unit_list
的条件中存在冲突的条件。实际上,您需要两次JOIN
至unit_list
,每个单位一次,以获得不同的块。请注意,您还需要在id_cat
条件中加入JOIN
,以免获得其他类别的商品。
SELECT
us.hits AS hits,
uc.slug AS cat,
ul1.slug AS slug_1,
ul2.slug AS slug_2
FROM unit_stats us
JOIN unit_cat uc ON uc.id_cat = us.id_cat
JOIN unit_list ul1 ON ul1.id_unit = us.id_unit_1 AND ul1.id_cat = uc.id_cat
JOIN unit_list ul2 ON ul2.id_unit = us.id_unit_2 AND ul2.id_cat = uc.id_cat
ORDER BY hits DESC
输出(用于您的演示数据)
hits cat slug_1 slug_2
16 weight kilogram gram
6 area square-meter square-kilometer
4 temperature celsius fahrenheit
2 distance meter exameter