[英]MySQL One to many, pulling only selected record from many table
I am quite new at SQL statements and I have never been very good at joins etc. I am having a problem working out how to do the following:我对 SQL 语句很陌生,而且我从来都不擅长连接等。我在解决如何执行以下操作时遇到问题:
I have 2 tables, one called MUSIC, one called REVIEWS.我有两张桌子,一张叫 MUSIC,一张叫 REVIEWS。 The two tables link on a field called uid - records in MUSIC are unique, but there may be many reviews for each MUSIC record.这两个表链接在一个名为 uid 的字段上 - MUSIC 中的记录是唯一的,但每个 MUSIC 记录可能有很多评论。
REVIEWS has a field called thumbsup, which is set to value 1 if a user gives a MUSIC the thumbs up. REVIEWS 有一个名为 thumbsup 的字段,如果用户对 MUSIC 竖起大拇指,则该字段设置为值 1。 Otherwise, the field is zero.否则,该字段为零。 There may be many thumbsup in REVIEWS, one thumbsup, or no thumbsup. REVIEWS 中可能有很多赞、一个赞或没有赞。
I am trying to display a list of records in MUSIC, and if there is a corresponding REVIEW record that contains a thumbsup value of 1 - just one record in REVIEWS will do it - then to display an icon on the list page.我正在尝试在 MUSIC 中显示记录列表,如果有相应的 REVIEW 记录包含拇指值 1 - 只有 REVIEWS 中的一条记录会执行此操作 - 然后在列表页面上显示一个图标。
I have had a good look around various similar questions but nothing quite like this comes up.我已经很好地查看了各种类似的问题,但没有出现像这样的问题。 I have tried doctoring around similar kinds of joins, but frankly how it all works is beyond me.我尝试过围绕类似的连接进行修改,但坦率地说,这一切是如何工作的,这超出了我的范围。 Sorry for being an idiot.对不起,我是个白痴。
By way of evidence that I have at least had a go, so far I have come up with this based on another post:作为证据,我至少有一个 go,到目前为止,我是根据另一篇文章提出的:
SELECT m.*, r.thumbsup
FROM (SELECT MAX(thumbsup) uid FROM reviews GROUP By uid) maxThumbs
INNER JOIN reviews r ON maxThumbs.uid = reviews.uid
INNER JOIN music m ON music.uid = reviews.uid
Needless to say it doesn't work:(不用说它不起作用:(
If anyone could help me out here with the right query structure I would be extremely grateful.如果有人可以通过正确的查询结构帮助我,我将不胜感激。
Many thanks非常感谢
Ted.特德。
select DISTINCT m.* from music m INNER JOIN reviews r on m.uid = r.uid where r.thumbsup > 0
How about something like this:像这样的东西怎么样:
SELECT m.*, IFNULL((SELECT 1 FROM reviews r WHERE r.thumbsup > 0 AND m.uid = r.uid LIMIT 1),0) has_review
FROM music m
SELECT m.*
FROM music m
INNER JOIN
(SELECT DISTINCT reviews.uid WHERE review.thumbsup > 0) r ON (r.uid = m.uid)
SELECT DISTINCT m.*, r.thumbsup
FROM music m LEFT JOIN reviews r
ON (m.uid = r.uid AND r.thumbsup=1);
Will return music records with no reviews, no positive reviews, mixed reviews, postivie only reviews (with any positive reviews indicated)将返回没有评论、没有正面评论、混合评论、仅 postivie 评论的音乐记录(显示任何正面评论)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.