我正在尝试构建一个简单的查询来获取具有特定元字段的用户(这是在Wordpress中,但无关紧要因为它是原始的sql)
我做的简单查询看起来像这样
SELECT * FROM wp_sb_users u
LEFT OUTER JOIN wp_sb_usermeta m ON (u.ID=m.user_id)
LEFT OUTER JOIN wp_sb_usermeta mm ON (u.ID=mm.user_id)
LEFT OUTER JOIN wp_sb_usermeta mmm ON (u.ID=mmm.user_id)
WHERE
m.meta_key = "autostatus" AND
mm.meta_key = "first_name" AND
mmm.meta_key = "last_name"
虽然我只有一个小麻烦 - 如果mmm.meta_key = "last_name"
根本不存在,则不返回该行..我尝试mmm.meta_key <=> "last_name"
但是它接受任何其他meta_key(如“ user_email“)并将其放入行中,然后导致用户名为Alex且姓氏为my@email.com
我也试过(mmm.meta_key =“last_name”或mmm.meta_key IS NULL),但它也不起作用
请帮我解决一下
PS 表结构:
CREATE TABLE IF NOT EXISTS `wp_sb_users` (
`ID` bigint(20) unsigned NOT NULL auto_increment,
`user_login` varchar(60) NOT NULL default '',
`user_pass` varchar(64) NOT NULL default '',
`user_nicename` varchar(50) NOT NULL default '',
`user_email` varchar(100) NOT NULL default '',
`user_url` varchar(100) NOT NULL default '',
`user_registered` datetime NOT NULL default '0000-00-00 00:00:00',
`user_activation_key` varchar(60) NOT NULL default '',
`user_status` int(11) NOT NULL default '0',
`display_name` varchar(250) NOT NULL default '',
PRIMARY KEY (`ID`),
KEY `user_login_key` (`user_login`),
KEY `user_nicename` (`user_nicename`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=30 ;
CREATE TABLE IF NOT EXISTS `wp_sb_usermeta` (
`umeta_id` bigint(20) unsigned NOT NULL auto_increment,
`user_id` bigint(20) unsigned NOT NULL default '0',
`meta_key` varchar(255) default NULL,
`meta_value` longtext,
PRIMARY KEY (`umeta_id`),
KEY `user_id` (`user_id`),
KEY `meta_key` (`meta_key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=792 ;
答案 0 :(得分:3)
SELECT * FROM wp_sb_users u
LEFT OUTER JOIN wp_sb_usermeta m ON (u.ID=m.user_id and m.meta_key = "autostatus")
LEFT OUTER JOIN wp_sb_usermeta mm ON (u.ID=mm.user_id and mm.meta_key = "first_name")
LEFT OUTER JOIN wp_sb_usermeta mmm ON (u.ID=mmm.user_id and mmm.meta_key = "last_name")