这是一个示例场景,假设我有一个社交媒体网站,例如facebook或其他什么,我想根据他们的电子邮件地址获取所有用户的照片ID。
以下是表格(基本表格)
x_users:
- user_id
- user_email
- user_pass
x_photos:
- photo_id
- user_id
如何使其成为查询结果,如:
SELECT * FROM x_users
LEFT JOIN x_photos ON x_users.user_id = x_photos.user_id
WHERE x_users.email = '...';
会返回这样的内容:(所有在一行中,至少)
+---------+------------+-------------+-------------+
| user_id | user_email | user_pass | user_photos |
+---------+------------+-------------+-------------+
| 1 | ... | my-password | 1,2,3,4,5 |
+---------+------------+-------------+-------------+
而不是:
+---------+------------+-------------+----------+
| user_id | user_email | user_pass | photo_id |
+---------+------------+-------------+----------+
| 1 | ... | my-password | 1 |
| 1 | ... | my-password | 2 |
| 1 | ... | my-password | 3 |
| 1 | ... | my-password | 4 |
| 1 | ... | my-password | 5 |
+---------+------------+-------------+----------+
答案 0 :(得分:1)
GROUP_CONCAT()适用于您的情况:
SELECT user_id, user_email, user_pass,
(SELECT GROUP_CONCAT(photo_id) FROM x_photos b WHERE b.user_id=a.user_id) AS photo_ids
FROM x_users a WHERE email = '...';