如何进行此选择查询?

时间:2015-06-06 09:02:15

标签: php mysql

我想在mysql中创建一个SELECT查询。

有两个表usersimage_info,需要选择以下列。

用户表:user_id, username, dob

image_info:image, image_path

选择图像时。我只需从im​​age_info表中获取主映像。在image_info表中有一个列,如:

  

image_type ENUM(' primary',' gallery')DEFAULT NULL,

这是我尝试的方式..

$q = "SELECT u.user_id, u.username, u.dob, i.image, i.image_path
            FROM users u 
                INNER JOIN image_info i ON i.user_id = u.user_id
            WHERE u.sex = 'Male'
            ORDER BY u.date_registered DESC LIMIT 6";

但它无法正常工作以获得我的预期输出。

更新 我的表输出..

mysql> select user_id, username, sex from users;
+---------+-------------+--------+
| user_id | username    | sex    |
+---------+-------------+--------+
|       1 | thara1234   | Male   |
|       2 | root234     | Male   |
|       3 | kamal123    | Female |
|       4 | Nilantha    | Male   |
|       5 | Ruwan324324 | Male   |
+---------+-------------+--------+
5 rows in set (0.00 sec)

mysql> select user_id, image, image_type from image_info;
+---------+----------------------------+------------+
| user_id | image                      | image_type |
+---------+----------------------------+------------+
|       2 | 2_root234_1433564588.jpg   | primary    |
|       1 | 1_thara1234_1433555104.jpg | primary    |
|       1 | 1_thara1234_1433556481.jpg | gallery    |
|       4 | 4_Nilantha_1433573768.jpg  | primary    |
+---------+----------------------------+------------+
4 rows in set (0.03 sec)

谢谢。

2 个答案:

答案 0 :(得分:1)

我认为,查询将是: -

SELECT User.user_id, User.username, User.dob, Image.image, Image.image_path
FROM 
    users User LEFT JOIN image_info Image
    ON User.user_id = Image.user_id AND Image.image_type = 'PRIMARY'
WHERE User.sex= 'Male'
ORDER BY User.date_registered DESC LIMIT 6

答案 1 :(得分:1)

正如您所说,您需要用户或者有图像,您应该在查询中使用左连接:

SELECT u.user_id, u.username, u.dob, i.image, i.image_path
            FROM users u 
                LEFT JOIN image_info i ON i.user_id = u.user_id
            WHERE u.sex = 'Male' and (i.image_type = 'primary' or i.image_type is null)
            ORDER BY u.date_registered DESC LIMIT 6;

See here了解更多信息。

相关问题