如何在mysql中构建此查询

时间:2013-01-28 14:40:07

标签: mysql sql

希望有人能帮我构建此查询。我需要从数据库中获取属于某个特定用户的值。这些是我需要的列。

01. city_name // From city table
02. district_name // From district table
03. category_name // From category table
04. subscription_period // From tutors table
05. date_registered // From tutors table

我已经分别获得了值tutor_id,city_id和category_id 1, 53, 5

我的地址表有city_id列,City表有district_id列,类别表有category_id列,教师表有tutor_id和{{1 }}

我试过这样的事情,但这不起作用。

address_id

我期望的结果应该有1行作为输出,但是这个查询给了我更多行作为输出

我的SQL表

SELECT city_name, district_name, category_name, subscription_period AS sp, date_registered AS date
FROM tutors AS t
INNER JOIN district AS d 
INNER JOIN city ON city.district_id = d.district_id
INNER JOIN address ON address.city_id = 50
INNER JOIN category
WHERE t.tutor_id = 1 AND category.category_id= 5

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

SELECT c.city_name, 
       d.district_name, 
       c.category_name, 
       t.subscription_period AS sp, 
       t.date_registered AS date
FROM tutors t
   INNER JOIN address a ON t.address_id = a.address_id 
   INNER JOIN city c ON c.city_id  = a.city_id 
   INNER JOIN district d ON c.district_id = d.district_id 
   INNER JOIN tutor_category tc on t.tutor_id = tc.tutor_id 
   INNER JOIN category cat on tc.category_id = cat.category_id 
WHERE t.tutor_id = 1 AND cat.category_id= 5 AND c.city_id = 50

您需要在表格上JOIN以确保只收到所需的结果。

如果您收到的是相同的重复行,则可能是您做错了或者您提供的定义不正确(看起来确实如此)。您可以通过在查询中添加GROUP BYDISTINCT来“解决”此问题,但这不是最佳方法。