MySQL查询结果未返回应包含在结果中的某些行

时间:2020-01-27 15:23:40

标签: mysql sql database

这是一个查询,应该返回找到的丢失物品​​的匹配结果。根据下面的数据库,我希望它返回两行,但仅返回一行。在将第二行添加到tbl_lost_items和tbl_found_items中之前,结果是一个空集。

SELECT L.user_id,L.item_type_id,F.found_by FROM tbl_users AS U 
      JOIN tbl_lost_items AS L ON U.id = L.user_id  
      JOIN tbl_item_types AS IT ON IT.id = L.item_type_id
      JOIN tbl_found_items AS F ON F.item_type_id = IT.id
   WHERE U.first_name = F.first_name_in_id AND U.last_name = F.last_name_in_id;

这是结果

+---------+--------------+----------+
| user_id | item_type_id | found_by |
+---------+--------------+----------+
|       6 |            3 |        4 |
+---------+--------------+----------+
1 row in set (0.01 sec)

这些是我的桌子

tbl_users

+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
|  1 | mohamed    | diaby     |
|  2 | estern     | winluck   |
|  3 | adam       | kisombe   |
|  4 | william    | patrick   |
|  5 | aisha      | diaby     |
|  6 | hanna      | shange    |
+----+------------+-----------+

tbl_found_items

+------------------+-----------------+--------------+----------+
| first_name_in_id | last_name_in_id | item_type_id | found_by | 
+------------------+-----------------+--------------+----------+
| mohamed          | diaby           |            1 |        2 |
| hanna            | shange          |            3 |        4 |
+------------------+-----------------+--------------+----------+

tbl_item_types

+----+-----------------------+
| id | item_type             |
+----+-----------------------+
|  1 | Citizen Identity Card |
|  2 | NHIF                  |
|  3 | Passport              |
|  4 | Voters Card           |
+----+-----------------------+

tbl_lost_items

+----+---------+--------------+---------------------+-----------+-----------+-------------+
| id | user_id | item_type_id | timestamp           | status    | region_id | district_id |
+----+---------+--------------+---------------------+-----------+-----------+-------------+
|  1 |       1 |            1 | 2020-01-26 18:58:04 | Not Found |         6 |          30 |
|  2 |       6 |            3 | 2020-01-27 14:12:19 | Not Found |        11 |          62 |
+----+---------+--------------+---------------------+-----------+-----------+-------------+

此外,当我在tbl_lost_items和tbl_found_items中删除应返回匹配项但不出现在查询结果中的行,然后在这两个表中再次重新输入相同信息时,结果将包含匹配项,但是如果在表tbl_lost_items和tbl_found_items中插入了一条应导致匹配的新记录,则匹配结果不会出现在查询结果中。我不知道这是什么问题。这是MySQL中的错误吗?我在Mac上使用的是MySQL 8.0.16。

1 个答案:

答案 0 :(得分:2)

join不匹配..在这种情况下,请使用左联接

您的某些值可能不匹配,请确保您没有使用TRIM()隐藏字符

 SELECT L.user_id,L.item_type_id,F.found_by FROM tbl_users AS U 
      JOIN tbl_lost_items AS L ON U.id = L.user_id  
      JOIN tbl_item_types AS IT ON IT.id = L.item_type_id
      JOIN tbl_found_items AS F ON F.item_type_id = IT.id
      WHERE  TRIM(U.first_name)  = TRIM(F.first_name_in_id)
      AND TRIM(U.last_name) = TRIM(F.last_name_in_id)