错误的SQL未知列' role_user.role_id'在' where子句'

时间:2018-05-19 22:35:37

标签: sql mysqli

我有以下代码:

SELECT * FROM `users` JOIN `role_user` ON `users.id` = `role_user.user_id` 
WHERE `role_user.role_id` = 2

架构表users

enter image description here

架构表role

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要在正确的位置设置反引号以转义some exception(表名和列名)。因此,您应该将查询更改为以下内容:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/background_light"
    tools:gridSpec="1|16|#0093eeff|K:#008080ff:16,l:72,l:16,r|S:#83ee00ff:16,0,l:16,56,l:16,0,r">

    <TextView
        android:text="Hallo World"
        android:layout_width="394.0dp"
        android:layout_height="68.5dp"
        android:id="@+id/textView1"
        android:textColor="@android:color/background_dark"
        android:textSize="36dp"
        android:layout_marginBottom="58.0dp"
        android:textAlignment="center" />
</LinearLayout>

答案 1 :(得分:1)

您的查询不需要所有的反引号。此外,我建议您使用表别名。更可读的查询形式如下:

SELECT *
FROM users u JOIN
     role_user ru
     ON u.id = ur.user_id 
WHERE ru.role_id = 2;

单个引用中的反引号之间的所有内容。所以,

`role_user.user_id`

是指具有该名称的单个列,而不是user_id中的列role_user。您可以引用您想要的列:

`role_user`.`user_id`

但这有点矫枉过正 - 难以打字,更难写。但是,一般情况下,请列出您的列和表名称,以便它们不需要转义。