我有两个表:users和user_meta。我想在与常规用户信息相同的查询中获取所有用户的元行。如何加入user_meta表的行,这些行在第一个表中可以作为列使用呢?
user_meta:user_id(int 15),context(varchar 250),value(varchar 250)
SELECT
m.user_id AS id, m.member_group_id, m.avatar_id, m.display_name, m.email_address, UNIX_TIMESTAMP(m.join_date) AS join_date, m.status,
l.member_id, COUNT(l.member_id) AS total_listings,
g.group_id, g.title AS group_title,
a.attachment_id, a.file_path AS avatar_path
FROM users AS m
LEFT JOIN user_meta AS meta ON m.user_id = meta.user_id
LEFT JOIN listings AS l ON l.member_id = m.user_id
LEFT JOIN groups AS g ON m.member_group_id = g.group_id
LEFT JOIN attachments AS a ON m.avatar_id = a.attachment_id
WHERE m.user_id = ".$id."
GROUP BY m.user_id
LIMIT 1
答案 0 :(得分:0)
只需尝试此m.user_id AS id ORDER BY ASC
答案 1 :(得分:0)
请澄清你的问题。 你提到2个表:用户&元数据,但在查询示例中,您有表列表,组和附件。 您要对哪个元数据字段进行排序?
请记住,要使count(l.member_id)正常工作,您必须将所有其他字段分组:
Group by m.user_id , m.member_group_id, m.avatar_id, m.display_name, m.email_address, UNIX_TIMESTAMP(m.join_date), m.status,
l.member_id, g.group_id, g.title ,
a.attachment_id, a.file_path
如果您不想按所有其他字段进行分组,则必须创建一个子查询,如下例所示,其中子查询用于计数。
SELECT
m.user_id AS id, m.member_group_id, m.avatar_id, m.display_name, m.email_address, UNIX_TIMESTAMP(m.join_date) AS join_date, m.status,
l.member_id,
(select COUNT(l.member_id) from listings where listings.member_id=m.user_id) AS total_listings,
g.group_id, g.title AS group_title,
a.attachment_id, a.file_path AS avatar_path
FROM users AS m
LEFT JOIN user_meta AS meta ON m.user_id = meta.user_id
LEFT JOIN listings AS l ON l.member_id = m.user_id
LEFT JOIN groups AS g ON m.member_group_id = g.group_id
LEFT JOIN attachments AS a ON m.avatar_id = a.attachment_id
WHERE m.user_id = ".$id."
order by
m.user_id
LIMIT 1