开发者

mysql query help - complicated join/order by scenario

开发者 https://www.devze.com 2022-12-18 13:03 出处:网络
I need to write a query and I\'m not even sure where to begin on this one. I have a set of tables that I did not create and开发者_如何学Python cannot change.

I need to write a query and I'm not even sure where to begin on this one. I have a set of tables that I did not create and开发者_如何学Python cannot change.

member table
+----+-------+
| id | class |
+----+-------+
|  1 |     1 |
|  2 |     2 |
+----+-------+

member_data table
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
|  1 |       John |     Jones |
|  2 |       Juan |     Jones |
+----+------------+-----------+

member_entries table
+----+-----------+-------+------------+
| id | member_id | title |    date    |
+----+-----------+-------+------------+
|  1 |         1 | test1 | 1265042580 |
|  2 |         1 | test2 | 1265042581 |
|  3 |         2 | test3 | 1265042582 |
|  4 |         3 | test4 | 1265042583 |
+----+-----------+-------+------------+

I need to select id, first_name from member_data, the most recent title from member_entries, and the total count of member_entries that matches the member_id. I need to be able to select where a member's class is a certain number in the first table. I also need to be able to order by any of those columns. This is what I need my output to be, if I selected members where member class is 1.

+----+------------+-------+------------+
| id | first_name | title |    date    |
+----+------------+-------+------------+
|  1 |       John | test2 | 1265042581 |
+----+------------+-------+------------+


 SELECT m.id, md.first_name, me.title, me.date
 FROM member m 
 INNER JOIN member_data md ON md.id = m.id 
 INNER JOIN member_entries me on me.id = m.id
 WHERE me.date =
   (SELECT MAX(date) FROM member_entries WHERE id = m.id)
 AND m.class = 1


SELECT member.id, member_data.first_name, member_entries.title, member_entries.date
FROM member
INNER JOIN member_data ON member.id = member_data.member_id
INNER JOIN member_entries ON member.id = member_entries.member_id
WHERE member.class = 1
ORDER BY member_entries.date DESC
LIMIT 1

and construct WHERE and ORDER BY clauses as you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消