如何从多个表中选择和匹配?

时间:2011-12-24 20:31:21

标签: php sql mysqli

这是我的表格布局:

-- Table structure for table `areas`
CREATE TABLE IF NOT EXISTS `areas` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) unsigned NOT NULL,
  `country` varchar(20) NOT NULL,
  `city` varchar(20) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- Table structure for table `matches`
CREATE TABLE IF NOT EXISTS `matches` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) unsigned NOT NULL,
  `view_id` bigint(20) unsigned NOT NULL,
  `status` enum('h','n') NOT NULL,
  `exp_date` date NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- Table structure for table `users`
CREATE TABLE IF NOT EXISTS `users` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `limit_age` varchar(5) NOT NULL DEFAULT '18:30',
  `limit_gender` varchar(2) DEFAULT NULL,
  `notifications` int(11) NOT NULL DEFAULT '0',
  `name` varchar(30) NOT NULL,
  `email` varchar(40) NOT NULL,
  `image_big` varchar(120) NOT NULL,
  `image_small` varchar(120) NOT NULL,
  `crop_data` int(11) DEFAULT NULL,
  `visible` tinyint(1) NOT NULL DEFAULT '0',
  `age` int(11) DEFAULT NULL,
  `registered_at` datetime NOT NULL,
  `views` bigint(20) unsigned NOT NULL DEFAULT '0',
  `hots` bigint(20) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;

我会尝试更好地解释这个:

我有一个给定的ID。 我想从users中选择一个不是我给出的ID的条目 和user_idmatches不存在 AND visible = 1 和country + city匹配给定用户的country + city

这是正确的方法(12是给定ID的示例):

SELECT *
FROM users a
INNER JOIN areas ON areas.user_id = a.id
WHERE a.id NOT IN (SELECT user_id FROM matches)
AND NOT a.id = '12'
AND a.limit_age = '18:30'
AND a.visible = '1'
AND areas.country = 'sverige'
AND areas.city = 'gbg'

很抱歉这个混乱:)

1 个答案:

答案 0 :(得分:0)

好的,我会尝试这个:

SELECT *
FROM users a
INNER JOIN areas ON areas.user_id = a.id
WHERE a.id NOT IN (SELECT user_id FROM matches)
AND a.visible = '1'
AND a.limit_age = '18:30'
AND a.limit_gender = 'f'
AND areas.country = ?
AND areas.city = ?;

这是从“用户”中选择,并且只有当该用户在“区域”表中也有一个条目时才返回结果。 WHERE子句中的第一项确保如果在“matches”表的user_id字段中找到users.id(a.id),则不会返回行。接下来,我在他的尝试中添加了对visible = 1,limit_age和limit_gender的检查。最后,我将country和city参数化,以便可以将它们作为参数添加到php代码中。如果有什么应该给你一个起点。