使用三向JOIN优化查询

时间:2014-03-21 19:47:35

标签: mysql performance join explain

我有以下查询建议使其更好以及如何避免空值。

SELECT stream.id AS status_id, 
       members.username, 
       members.membership_type, 
       members.first_name, 
       members.last_name, 
       stream.member_id, 
       stream.url_preview,
       stream.media,
       stream.images,  
       stream.poll_id, 
       stream.status_type, 
       stream.created_at, 
       stream.activity_text, 
       stream.original_id, 
       stream.shared_from 
FROM stream, follow, members 
WHERE follow.follower_id = 239 
AND stream.member_id = members.id
AND (stream.member_id=follow.follower_id OR stream.member_id=follow.member_id) 
AND stream.type = 2 
AND stream.status_type NOT IN (4, 5, 7, 8, 9, 10, 11) 
GROUP BY stream.id 
ORDER BY stream.id DESC 
LIMIT ' . $offset . ', 10;

+----+-------------+---------+--------+-----------------------+-------------+---------+-------------------------+------+-------------+
| id | select_type | table   | type   | possible_keys         | key         | key_len | ref                     | rows | Extra       |
+----+-------------+---------+--------+-----------------------+-------------+---------+-------------------------+------+-------------+
|  1 | SIMPLE      | stream  | index  | member_id             | PRIMARY     | 4       | NULL                    |    1 | Using where |
|  1 | SIMPLE      | members | eq_ref | PRIMARY               | PRIMARY     | 4       | portal.stream.member_id |    1 |             |
|  1 | SIMPLE      | follow  | ref    | follower_id,member_id | follower_id | 4       | const                   |   14 | Using where |
+----+-------------+---------+--------+-----------------------+-------------+---------+-------------------------+------+-------------+

1 个答案:

答案 0 :(得分:0)

是的,很明显你使用旧的加入方式,如果你需要避免在数据上显示NULL值,那么你可以使用IFNULL()函数来避免NULL。

示例: -

select ifnull(members.username,'this is null part') as username from table_name;

此查询将打印null部分,如果用户名为null,则它将仅打印用户名。

您可以在查询中提取列数据时应用于所有列。

希望它会对你有所帮助。