开发者

Simplify massive mysql query

I currently have 3 tables called reports, users and clients

reports has 5 fields, respectively:

report_id INT,
user_id INT (FK to users on user_id)
client_id INT (FK to clients on client_id)
create_date DATE
description TEXT

users has 4 fields, respectively

user_id INT
username VARCHAR
password VARCHAR
parent_id INT (FK to users on user_id)

clients has 3 fields, respectively

client_id INT
firstname VARCHAR
lastname VARCHAR

As you can see, a user is allowed to have a parent user (an administrator of some sort). I want to fetch all reports created by parent users and regular users and display them. I already figured out a query to do this, but it's quite massive.

eg: fetch all reports of parent user with id 4 and all their childrens reports.

(SELECT c.firstname, c.lastname, r.report_id, r.date, u.name 
 FROM clients c, reports r, users u 
 WHERE u.users_id=4 
 AND r.user_id = u.users_id 
 AND c.client_id = r.client_id) 
UNION 
(SELECT c.firstname, c.lastname, r.report_id, r.date, u.name 
 FROM clients c, reports r, users u 
 WHERE u.parent_id=4 
 AND r.user_id = u.users_id 
 AND c.client_id = r.client_id);

Is there any way to simplify this query? 开发者_Go百科I'm all out of luck figuring it out.

Thanks in advance;


you can use OR as the 2 queries are almost identical

SELECT * 
FROM clients c, reports r, users u 
WHERE r.user_id = u.users_id 
  AND c.client_id = r.client_id
  AND (u.users_id=4 OR u.parent_id=4)


How about:

SELECT firstname, lastname, report_id, date, name
FROM   clients NATURAL JOIN reports NATURAL JOIN users
WHERE  users_id=4 OR parent_id=4


Has anyone heard of JOINing?

SELECT
   firstname, lastname, report_id, date, name
FROM
   clients
   JOIN reports USING (client_id)
   JOIN users USING (report_id)
WHERE
   user_id = ?
   OR parent_id = ?
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜