以下是表格:
表用户:
User_Id = 1,2,3;
User_Name: A,B,C;
表业务:
Business_Id = 1,2,3;
Business_Name: A,B,C;
Business_Detail: Details_A, Details_b, Details_c;
表访问:
Visit_Id = 1,2,3,4,5,6:
User_Id = 1,1,1,2,1,1;
Business_Id = 1,1,1,2,2,3;
我需要创建一个函数,该函数返回访问列表以及用户访问的业务信息。到目前为止,我已经获得了用户访问过的商店列表,但不知道该去哪里。
function visit_count($user_id=1){
global $database;
$sql = "SELECT * FROM visits WHERE user_id ='{$user_id}' LIMIT 0 , 30";
$result_set = $database->query($sql);
$visits = mysql_fetch_array($result_set);
//Get the unique ids of the business
//Run another query that has the business information
//combing both queries.
}
感谢快速回复的人。它正是我正在寻找的东西我认为我正在寻找一个返回一个对象的查询如下:
Object:
- Business:
- Business_id;
- Business_name;
- Visit_counts;
- Business:
- Business_id;
- Business_name;
- Visit_counts;
因此,基本上该对象将具有业务信息,并且没有用户访问商店的次数。
非常感谢所有帮助
答案 0 :(得分:0)
你需要加入:
SELECT v.*, b.Business_Name, b.Business_Detail FROM visits as v
JOIN Business as b on b.Business_Id = v.Business_Id
WHERE v.user_id ='{$user_id}' LIMIT 0 , 30
另外 - 使用mysqli并确保你是sanitizing your inputs!
修改强>
关注@ KHMKShore关于使用预准备陈述的建议。
答案 1 :(得分:0)
嗯,首先你应该研究prepared statements,这是目前在PHP中使用sql的最佳实践。
你需要的是加入。
$sql = "SELECT * FROM visits v
JOIN business b ON b.Business_Id = v.Business_Id
JOIN user u ON u.Business_Id = v.Business_Id
WHERE v.user_id ='{$user_id}' LIMIT 0 , 30";
答案 2 :(得分:0)
SELECT Visits.* , Business.Business_Name, Business.Business_Details
FROM Visits
LEFT JOIN Business on Business.Business_Id = Visits.Business_Id
WHERE Visits.User_Id =1
为每个用户尝试此SQL
答案 3 :(得分:0)
尝试以下SQL代码:
SELECT business.business_id, business.business_name, COUNT(business.business_id) AS visit_counts
FROM business
LEFT JOIN visits
ON business.business_id = visits.business_id
GROUP BY business_id, user_id
结果:
business_id |business_name |visit_counts
1 A 3
2 B 1
2 B 1
3 C 1