我需要来自2个不同表格的双重SELECT sql查询,其中包含名称访问和放大项目 1:SELECT visitid,visitdate,visitreason FROM visits WHERE personid = 10 2:SELECT itemid,itemname,itemtime FROM items WHERE itemvisitid = visitid 我想我需要做一个JOIN,但不知道究竟是怎么做的。
表格示例:
表:访问次数
visitid | personid | visitdate | visitreason
1 | 10 | 05/07/2014 | no reason
2 | 10 | 06/07/2014 | some reason
3 | 12 | 06/07/2014 | no reason
4 | 10 | 12/07/2014 | some other reason
表:项目
itemid | personid | itemvisitid | itemname | itemtime
1 | 10 | 2 | box | 23
2 | 10 | 2 | clock | 70
3 | 10 | null | water | 50
4 | 10 | null | paper | 40
5 | 12 | 3 | box | 26
我现在拥有的是:
$query = "SELECT visitid, visitdate, visitreason FROM visits WHERE personid = '10' ORDER BY visitdate DESC";
// 2nd select: "SELECT itemid, itemname, itemtime FROM items WHERE itemvisitid= visitid";
$db->setQuery($query);
$results = $db->query();
while($row = mysqli_fetch_array($results)){
echo "<tr>
<td>".$row['visitid'].", ".$row['visitdate']."</td>
<td>".$row['visitreason']."</td>
<td>".$row['itemid'].",".$row['itemname'].", ".$row['itemtime']."</td>
</tr>";
}
我需要结果是这样的:
<tr>
<td>1, 05/07/2014</td><td>no reason</td><td></td>
<td>2, 06/07/2014</td><td>some reason</td><td>1, box, 23<br />2, clock, 70</td>
<td>4, 12/07/2014</td><td>some other reason</td><td></td>
</tr>
答案 0 :(得分:0)
SELECT `visits`.`visitid`, `visits`.`visitdate`, `visits`.`visitreason`,`items`.`itemname`, `items`.`itemtime` from `visits` INNER JOIN `items` ON `visits`.`personid`=`items`.`personid` WHERE `visits`.`personid` = '10' ORDER BY `visits`.`visitdate` DESC
如果有任何错误,请更改'items'表中的字段名称personid,然后检查。
答案 1 :(得分:0)
此查询:
SELECT v.visitid,
v.visitdate,
v.visitreason,
i.itemid,
i.itemname,
i.itemtime
FROM visits v
INNER JOIN items i
ON ( v.visitid = i.itemvisitid )
WHERE v.person_id = 10
ORDER BY v.visitdate DESC,
i.itemid ASC
将链接两个表并生成一个可以使用双循环遍历的结果集。外部循环用于处理对访问的更改,而内部用于添加在特定访问中访问的每个项目。
答案 2 :(得分:0)
我想您可能会像这样使用GROUP_CONCAT
:
DEMO:http://sqlfiddle.com/#!2/9d4e22/15
SELECT visitid, DATE_FORMAT(visitdate,'%m/%d/%Y'), visitreason,
GROUP_CONCAT(itemid,itemname, itemtime)
FROM visits left join items on visits.visitid = items.itemvisitid
WHERE visits.personid = 10
GROUP BY visitid, visitdate, visitreason
您可能需要阅读此内容以了解GROUP_CONCAT
:
How to use GROUP_CONCAT in a CONCAT in MySQL
GROUP_CONCAT()
的文件在这里:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
希望这有帮助。