简体   繁体   English

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

[英]MySQL Query Two Tables with different column lookup

How to make this syntax works : 如何使此语法有效:

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)

Your LIKE clause is faulty. 您的LIKE子句有问题。 I suspect that you intend to use an IN() clause instead: 我怀疑您打算改用IN()子句

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

If you are trying to match partial strings with LIKE , you need to OR them together in a () group, as in: 如果您尝试使用LIKE匹配部分字符串,则需要在()组中对它们进行“ OR ,例如:

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

Note also, that the implicit join syntax you are using (comma-separated tables) is deprecated in favor of an explicit JOIN . 还要注意,不赞成使用您使用的隐式连接语法(用逗号分隔的表),而推荐使用显式的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')

Finally, I would recommend explicitly naming the columns you want rather than doing SELECT * , so you get them in a deterministic order, and guard against the addition of other columns later that you don't need in this query: 最后,我建议显式命名您想要的列,而不要执行SELECT * ,这样您就可以按确定的顺序获取它们,并避免以后再添加此查询中不需要的其他列:

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

Does this work? 这样行吗?

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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM