SQL查询问题(带截图)

时间:2011-11-16 04:11:45

标签: php mysql sql

我有三张桌子:

Shop
Shop_id  City_id   Address  
1        1         Address 1      
2        1         Address 2
3        2         Address 3 
4        2         Address 4
5        1         Address 5
6        1         Address 6

City
City_id  Name
1        Vilnius
2        Kaunas

Places
Place_id  Shop_id  Book_id
1         3        1
2         2        1
3         3        2
4         4        3
5         3        3

Places表格中,我保存了可以购买特定图书的商店。 我也有复选框形式:

$result = mysql_query("SELECT places.place_id, places.book_id, places.shop_id,
shop.shop_id, shop.city_id,shop.address,city.city_id,city.name 
FROM shop INNER JOIN places ON places.shop_id=shop.shop_id 
INNER JOIN city ON shop.city_id=city.city_id") or die(mysql_error());

if(mysql_num_rows($result) > 0) {
    while($row = mysql_fetch_assoc($result2)) {
        echo '<tr> 
                <td><input type="checkbox"'; if ($row['book_id']==$id2){echo 'checked';}echo' name="identifer[]" value="'.$row['shop_id'].'" /> <br /></td>  
                <td>'.ucfirst($row['Name']).','.$row['Address'].' </td> 
             </tr> 

如果Book_id等于$id2,我尝试使用带有checbox检查值的所有可用商店创建表格。 更清楚的是截图,它显示了我从代码中获得的内容:

enter image description here

显然,它基本上写下了Places表中的所有商店。我试图更改我的SQL代码,但我无法正确使用,所以我需要帮助。

5 个答案:

答案 0 :(得分:2)

我认为您的问题无法通过LEFT JOIN解决,因为您可以Places获得多个Shop。试试这个:

SELECT EXISTS (SELECT * FROM places p
               WHERE  p.shop_id = s.shop_id AND p.Book_id = $id2) AS has_book
      ,s.shop_id, s.city_id, s.address
      ,c.city_id, c.name 
FROM   shop s
JOIN   city c USING (city_id)  -- or LEFT JOIN if city could be missing

或者,如果保证(Shop_id, Book_id)是唯一的 - 这意味着一本书永远不会在商店中出现多次 - 您希望包含来自Places的列,你可以使用这样的查询:

SELECT p.place_id, p.book_id, p.shop_id
      ,s.shop_id, s.city_id, s.address
      ,c.city_id, c.name 
FROM   shop s
JOIN   city c USING (city_id)  -- or LEFT JOIN if city could be missing
LEFT   JOIN places p ON p.shop_id = s.shop_id AND p.Book_id = $id2

请注意ON的{​​{1}}子句中的附加条件。必须在那里,而不是在LEFT JOIN条款中。 这样,每个商店都会为 商店添加数据,如果它有图书的话。由于商店只能拥有一本书,所以没有商店会加倍。

答案 1 :(得分:1)

你正在两张桌子上进行INNER JOIN。这意味着查询将返回仅在连接的两侧存在数据的记录。您的位置表仅列出商店2,3,4。因此,不会返回Shops表中ID为1,5,6的记录,因为没有匹配的Places记录。

答案 2 :(得分:0)

尝试用LEFT JOINS替换INNER JOINS

答案 3 :(得分:0)

Shop LEFT JOIN Places LEFT JOIN CityGROUP BY shop_id

答案 4 :(得分:0)

为什么不将id2的查询传递给查询?如果我正确理解你的问题:

$query = sprintf("SELECT places.place_id, places.book_id, places.shop_id,
shop.shop_id, shop.city_id,shop.address,city.city_id,city.name 
FROM shop INNER JOIN places ON places.shop_id=shop.shop_id 
INNER JOIN city ON shop.city_id=city.city_id
AND places.Place_id='%s'",mysql_real_escape_string($id2));

$result = mysql_query($query);