MySQL查询两个具有不同列查找的表

时间:2012-05-25 16:04:09

标签: mysql

如何使这种语法有效:

SELECT * 
FROM
  uploads,
  audienceuploadassociation 
WHERE 
  uploads.member_id = '1'
  AND uploads.member_school_id='1' 
  AND subject = 'Maths' 
  AND uploads.upload_id = audienceuploadassociation.upload_id 
  AND topic = 'Integers' 
  AND year IN(7, 8, 9) 
  AND audienceuploadassociation.audiencename LIKE (Parents, Teachers, Community)

2 个答案:

答案 0 :(得分:3)

您的LIKE条款有误。我怀疑您打算使用an IN() clause代替:

AND audienceuploadassociation.audiencename IN ('Parents', 'Teachers', 'Community')

如果您尝试将部分字符串与LIKE匹配,则需要在OR组中()将它们放在一起,如:

AND (
  audienceuploadassociation.audiencename LIKE 'Parents%'
  OR audienceuploadassociation.audiencename LIKE 'Teachers%'
  OR audienceuploadassociation.audiencename LIKE 'Community%'
)

另请注意,不推荐使用您使用的隐式连接语法(以逗号分隔的表),而使用显式JOIN

SELECT
  uploads.*,
  audienceuploadassociation.*
FROM
  /* Explicit JOIN  with ON clause */
  uploads
  JOIN audienceuploadassociation ON uploads.upload_id = audienceuploadassociation.upload_id 
WHERE 
  uploads.member_id = '1'
  AND uploads.member_school_id='1' 
  AND subject = 'Maths' 
  AND topic = 'Integers' 
  AND year IN(7, 8, 9) 
  AND audienceuploadassociation.audiencename IN ('Parents', 'Teachers', 'Community')

最后,我建议明确命名所需的列而不是SELECT *,因此您可以按照确定的顺序获取它们,并防止在此查询中不需要添加其他列:

SELECT 
  uploads.upload_id,
  uploads.other_column,
  uploads.topic,
  audienceuploadassociation.audiencename,
  ...
  ...

答案 1 :(得分:0)

这有用吗?

SELECT * 
FROM
  uploads,
  audienceuploadassociation 
WHERE 
  uploads.member_id = '1'
  AND uploads.member_school_id='1' 
  AND subject = 'Maths' 
  AND uploads.upload_id = audienceuploadassociation.upload_id 
  AND topic = 'Integers' 
  AND year IN(7, 8, 9) 
  AND audienceuploadassociation.audiencename IN ('Parents', 'Teachers', 'Community');