多表MySQL查询

时间:2012-06-07 18:40:23

标签: mysql

我有两个表,我想同时查询。这些表是上传和audienceuploadassociation,所以这里是东西,我的表中只有一个名为“ESL”的主题值,但是当我使用下面的SQL时,它给我6条记录,它重复相同的数据6次。

SELECT uploads.*, audienceuploadassociation.*
FROM   uploads
  JOIN audienceuploadassociation
    ON uploads.upload_id = audienceuploadassociation.upload_id
 WHERE uploads.member_id = '1'
   AND uploads.member_school_id='1'
   AND subject = 'ESL'
   AND topic = 'Poetry'
LIMIT  20

以下是上传的表格结构:

`uploads` (
  `upload_id` int(11) NOT NULL AUTO_INCREMENT,
  `member_id` varchar(255) NOT NULL,
  `date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `upload_name` text NOT NULL,
  `upload_title` varchar(255) NOT NULL,
  `upload_type` varchar(100) NOT NULL,
  `subject` varchar(50) NOT NULL,
  `topic` longtext NOT NULL,
  `year` int(100) DEFAULT NULL,
  `keywords` varchar(255) NOT NULL,
  `description` longtext NOT NULL,
  `status` enum('Finished','Work in progress','Blank template') NOT NULL DEFAULT 'Finished',
  `test_name` varchar(255) DEFAULT NULL,
  `firstname` varchar(255) NOT NULL,
  `lastname` varchar(255) NOT NULL,
  `member_display_name` varchar(255) NOT NULL,
  `member_school_id` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`upload_id`)
) 

和audienceuploadassociation:

`audienceuploadassociation` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `upload_id` bigint(20) NOT NULL,
  `audiencename` varchar(254) NOT NULL,
  PRIMARY KEY (`id`)
) 

任何帮助将不胜感激,提前谢谢。

2 个答案:

答案 0 :(得分:0)

试试这个,使用GROUP BY:

SELECT uploads.*, audienceuploadassociation.*
FROM   uploads
  JOIN audienceuploadassociation
    ON uploads.upload_id = audienceuploadassociation.upload_id
 WHERE uploads.member_id = '1'
   AND uploads.member_school_id='1'
   AND subject = 'ESL'
   AND topic = 'Poetry'
GROUP BY uploads.upload_id
LIMIT  20

答案 1 :(得分:0)

我认为这两个表之间没有任何关系。

uploads表定义中更改此

`member_school_id` int(11) NOT NULL DEFAULT 1

member_school_id删除引用,因为它是INT字段。

SELECT uploads.*, audienceuploadassociation.*
FROM   uploads
  JOIN audienceuploadassociation
    ON uploads.upload_id = audienceuploadassociation.upload_id
 WHERE uploads.member_id = '1'
   AND uploads.member_school_id=1
   AND uploads.subject = 'ESL'
   AND uploads.topic = 'Poetry'
LIMIT  20