我有3张桌子:
wp_users
- 存储有关所有用户的主要信息,wp_usermeta
- 存储有关用户的附加信息(名/姓)等,wp_friends
- 存储来自与wp_users
如果您不熟悉WordPress,可以在http://codex.wordpress.org/images/9/9e/WP3.0-ERD.png
查看两个表格的结构我的自定义表格wp_friends
的结构如下:
CREATE TABLE wp_friends (
id bigint(20) unsigned NOT NULL auto_increment,
uid bigint(20) unsigned NOT NULL default '0',
fr_id VARCHAR (60) NOT NULL default '',
service VARCHAR (20) NOT NULL default '',
name VARCHAR (80) NOT NULL default '',
photo VARCHAR (255) NOT NULL default '',
PRIMARY KEY (id),
KEY uid (uid),
KEY fr_id (fr_id),
KEY service (service)
)`
uid
列对应ID
表中的wp_users
列 - 这就是我如何确定哪个记录对应哪个用户。
我要做的是创建一个查询,该查询将在所有三个表中查找与关键字匹配的内容。这是我到目前为止所提供的内容(第一部分是由WordPress的搜索功能生成的):
SELECT
wp_users.ID,wp_users.display_name,wp_users.user_login,
wp_users.user_email,fr.fr_id,fr.name,fr.photo,fr.service
FROM wp_users
INNER JOIN wp_usermeta ON (wp_users.ID = wp_usermeta.user_id)
LEFT JOIN wp_socialaccess_friends AS fr ON fr.uid = 2
WHERE
(
(user_login LIKE '%nik%' OR user_nicename LIKE '%nik%')
AND
(wp_usermeta.meta_key = 'wp_user_level' AND CAST(wp_usermeta.meta_value AS CHAR) != '0')
)
OR ( fr.uid = 2 AND (fr.fr_id LIKE '%nik%' OR fr.name LIKE '%nik%'))
GROUP BY wp_users.ID,fr.fr_id ORDER BY user_login ASC
在上面的查询中,关键字是“nik”(也与user_login
列匹配)。需要fr.uid
部分,因此返回的结果仅适用于当前用户。查询以下列方式失败:
wp_friends
表中的所有行(因为user_login
列也匹配),具有wp_friends.uid = 2
wp_friends.uid = 2
但与wp_users.ID != 2
是否可以创建单个查询,返回所选列,但也可以防止重复?
答案 0 :(得分:3)
如何加入以下的子选项:
SELECT
wp_users.ID,wp_users.display_name,wp_users.user_login,
wp_users.user_email
FROM wp_users
INNER JOIN wp_usermeta ON (wp_users.ID = wp_usermeta.user_id)
left join(
select fr_id, uid,name,photo,service from wp_socialaccess_friends where
uid = 2 and
(fr_id LIKE '%nik%' OR name LIKE '%nik%')
) AS fr ON wp_users.ID = fr.uid
WHERE
(
(user_login LIKE '%nik%' OR user_nicename LIKE '%nik%')
AND
(wp_usermeta.meta_key = 'wp_user_level' AND CAST(wp_usermeta.meta_value AS CHAR) != '0')
)
GROUP BY wp_users.ID,fr.fr_id ORDER BY user_login ASC