MySQL加入语法错误

时间:2014-08-28 23:08:46

标签: mysql sql

我正在尝试同时加入3张桌子以获得"学校名称"来自schools_informations表和"用户ID,用户名,用户姓氏"从登录表。

我需要做的是获取用户数据",#34;学校数据"然后使用user_id表格中的school_idasc_to_school进行匹配。

这是我的schools_informations表,我需要将school_id与asc_to_schools表和schools_name中的匹配显示为输出($ variable):

 id | school_id | school_name     | school_type     | type | la_name         | region 
----+-----------+-----------------+-----------------+------+-----------------+--------
 1  | 8432627   | Glasgow Gaelic  | Local Authority | Both | Glasgow City    | WE
 2  | 5349834   | Breadalbane     | Local Authority | Both | Perth & Kinross | TF
 3  | 7235142   | ForestFortres   | Local Authority | Both | undefined       | WE

这是我的登录表:

 id | username | pass | region | la               | name  | surname | role
----+----------+------+--------+------------------+-------+---------+------
 1  | Can      | **** |  none  | Clackmannanshire | Can   | Sinal   | ASC
 2  | Tumer    | **** |  none  | Argyll & Bute    | Tumer | Kologlu | GM
 3  | Kerem    | **** |  none  | Somethingelse    | Kerem | Citak   | ADM
 4  | Pelin    | **** |  none  | Somethingelse    | Pelin | Karahan | GM
 5  | Irem     | **** |  none  | Somethingelse    | Irem  | Sevinc  | CC

最后,我的asc_to_school表格如下:

 user_id | school_id
---------+-----------
    1    | 1
    2    | 1
    3    | 2
    4    | 2
    5    | 3

这是我试过的一个查询:

SELECT 
u.id, u.name, u.surname, u.role, 
c.user_id, c.school_id, 
s.school_id,s.school_name 
FROM login u, asc_to_school c, school_informations s 
WHERE u.role = 'ASC' AND c.user_id = u.id AND c.school_id = s.id

你可以猜到SQL返回了一个空的结果......我搜索了这个并找到了这个例子(我在另一个问题中试过的查询),但它对我没用。

我怎样才能得到: 只有具有"角色"的用户=" ASC" 并使用asc_to_school表格将此用户与学校联系起来。

修改

这是我在SQL Fiddle中使用的最后一个查询:

SELECT 
u.id, u.name, u.surname, c.school_id, 
s.school_id,s.school_name 
FROM login u, asc_to_school c, school_informations s 
WHERE u.role = 'ASC' AND c.user_id = u.id AND c.school_id = s.id

结果如下:

object(mysqli_result)#3 (5) {
  ["current_field"]=>
  int(0)
  ["field_count"]=>
  int(5)
  ["lengths"]=>
  NULL
  ["num_rows"]=>
  int(0)
  ["type"]=>
  int(0)
}

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT 
    u.id, 
    u.name, 
    u.surname, 
    u.role, 
    c.user_id, 
    s.school_id, 
    s.school_name 
FROM login u 
INNER JOIN asc_to_school c ON c.user_id = u.id 
INNER JOIN school_informations s ON s.id = c.school_id 
WHERE TRIM(u.role) = 'ASC'

答案 1 :(得分:0)

使用明确的JOIN语法,更容易理解和维护:

SELECT u.id, u.name, u.surname, u.role
     , c.user_id, c.school_id
     , s.school_name
FROM   login u
JOIN   asc_to_school       c ON c.user_id   = u.id 
JOIN   school_informations s ON s.school_id = c.school_id  -- ?not s.id?
WHERE  u.role = 'ASC';

我怀疑你真的想加入s.school_id?您的示例另有说明,但我怀疑 示例 中的数据具有误导性。你的文字说:

  

以下是我的schools_informations表格,我需要使用 school_id 并在asc_to_schools表格中将其匹配

大胆强调我的 school_id SELECT列表中重复出现。许多客户端不会吞下重复的列名。