[英]logical issue with SQL query dealing with two tables
道歉,因为我对SQL相当陌生,但是我无法找到问题的解决方案。
我有两个表格概述如下:
评论表
列:名称,评论,等级a,等级b,等级c,会场ID
场地表
列:ID,场地名称,描述,地址
我想从会场表中获得名称,其中同一行中的ID与注释表中会场ID的ID匹配,这可能吗? (venue_id和id匹配)
例如,如果我要打印此文件,我将拥有
venue_name (from the venue table) rating a (from the comment table) rating b (from the comment table) rating c (from the comment table)
(评分通过评论表中的场地ID和场地表中的ID链接到场地名称)
对此表示歉意,但如果可能的话,将不胜感激。 谢谢
使用简单联接查询。 SELECT Venue.venue_name, Comment.rating_a, Comment.rating_b, Comment.rating_c FROM Venue INNER JOIN Comment ON Venue.id=Comment.venue_id;
这将为您提供:
select Venue.venue_name,
rating_a, rating_b,
rating_c from Venue,
Comment
where Comment.venue_id = Venue.id;
说明:
Venue.venue_name和三个rating_标识符都告诉SQL您要输出哪些列(请注意:您可能必须在三个rating列之前添加Comment。,但是我认为如果没有这些列,它们就可以工作,因为这些列是唯一命名的) 。
from语句必须包含要从中提取数据的每个表(无论是用于显示还是用于where子句)。
最后,where子句是Venue中的行与Comment中的行相关的方式(它们共享一个通用的场所ID)。 您需要确保Venue中的destination_id是主键(理想情况下,将其设置为auto_increment)
您可能需要在场所表中为ID设置参考键。 只需将venue_id作为主键,然后将其引用到Venue表中的id即可。
所以SQL查询将是-
SELECT venue.venue_name,
rating_a.comment,
rating_b.comment
FROM venue, comment
INNER JOIN venue
ON Comment.venue_id = Venue.id;
或只是在哪里使用
select Venue.venue_name,
rating_a,
rating_b
from Venue, Comment
where Comment.venue_id = Venue.id;
首先要注意的是,在连接这两个表时,您需要设置主键和外键...对于Venue表,请设置主键,然后设置外键。 您可以将Venue表的主键设置为自动增量,然后将外部键的-id-引用到Comment表中的destination_id。
您可以使用SQL JOIN
尝试
SELECT s.*, AS venue_name
FROM venuetable s
LEFT JOIN commenttable
AS r
ON r.venue_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.