[英]How do I make this select query?
I want to create a SELECT
query in mysql. 我想在mysql中创建一个
SELECT
查询。
There are two tables, users
and image_info
, and need to select following columns. 有两个表,
users
表和image_info
,需要选择以下列。
user table : user_id, username, dob
用户表:
user_id, username, dob
image_info : image, image_path
image_info:
image, image_path
When selecting image. 选择图像时。 I need to get only primary image from image_info table.
我只需要从image_info表中获取主图像。 In image_info table there is a column like:
在image_info表中有一个类似列:
image_type ENUM('primary', 'gallery') DEFAULT NULL,
image_type ENUM('primary','gallery')DEFAULT NULL,
This is how I tried it.. 这就是我尝试过的方法。
$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";
But it doesn't work properly to get my expected output. 但是无法获得我的预期输出。
UPDATE: my table outputs.. 更新:我的表输出。
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)
Thank you. 谢谢。
I think, query would be :- 我认为,查询将是:-
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
As you said you need the user either he has an image or not you should use left join in your query: 如您所说,您需要用户拥有图像或没有图像,您应该在查询中使用左连接:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.