如何创建JOIN查询MYSQL?

时间:2015-10-02 00:17:23

标签: php mysql sql console

我有2个mysql表:cs_lots& cs_lots_history。相关:id = id_lot

Таблица cs_lots_history

Таблица cs_lots

我需要编写一个查询,在数组中显示每批cs_lots的ID,如果ID = ID_LOT,则需要显示cs_lots_history user_personaname的ID 查询,我有:

SELECT cs_lots_history.*, cs_lots.id as csid, inv_id, inv_assets, inv_image, inv_color, inv_name, inv_rarity, inv_type, inv_price, price_ticket, places, now_places FROM cs_lots LEFT JOIN cs_lots_history ON cs_lots.id = cs_lots_history.id_lot WHERE active_lot='1' AND user_personaname='@Saundefined' GROUP BY cs_lots.id;

但事实上它只需要6手,因为表cs_lots_history尼克@ Saundefined只购买了6个(唯一的id_lots)。如果他们不这样做,结果就不会打印出来了

如果您没有指定条件WHERE user_personaname - 然后获得所有12个批次,但是没有查询意识,该数组将不会被用户获得此购买项目..

如果cs_lotscs_lots_history id = id_lot找不到昵称,我希望这样做会显示所有12个项目,重点放在$rows = array(); $res2 = mysql_query("SELECT cs_lots_history.*, cs_lots.id as csid, inv_id, inv_assets, inv_image, inv_color, inv_name, inv_rarity, inv_type, inv_price, price_ticket, places, now_places FROM cs_lots LEFT JOIN cs_lots_history ON cs_lots.id = cs_lots_history.id_lot WHERE active_lot='1' AND user_steamid='".$_SESSION['steamid']."' GROUP BY cs_lots.id") or die(mysql_error()); while($row = mysql_fetch_array($res2)) { $rows []= array( 'id' => $row['csid'], 'inv_id' => $row['inv_id'], 'inv_assets' => $row['inv_assets'], 'name' => $row['inv_name'], 'inv_image' => $row['inv_image'], 'inv_rarity' => $row['inv_rarity'], 'inv_color' => $row['inv_color'], 'inv_type' => $row['inv_type'], 'inv_price' => $row['inv_price'], 'price_ticket' => $row['price_ticket'], 'maxUsers' => $row['places'], 'nowUsers' => $row['now_places'], 'my' => !empty($row['id_lot']) ? true : false ); } 上。在列中简单为NULL。 有可能吗?

P.S。我的PHP代码,如果需要.. - :

//returns the area of a trapezoid
public double getArea(){
    double height = getHeight();
    double area = (.5 * ((getPoint(3).getX() - getPoint(4).getX()) + (getPoint(2).getX() - getPoint(1).getX()))) * height;
    return area;
}

//returns the height of a trapezoid
public double getHeight(){
    double area = getArea();
    double height = (2 * area) / (((getPoint(3).getX() - getPoint(4).getX()) + (getPoint(2).getX() - getPoint(1).getX())));
    return height;
}

1 个答案:

答案 0 :(得分:0)

很难理解你所追求的是什么。我相信你想要一个返回cs_lot表中所有记录的查询,并指出客户是否使用历史表从该批购买:

select cs_lots.id, count(h.id) from cs_lots left join cs_lots_history h
on cs_lots.id=h.id_lot and h.personaname='...'
where cs_lots.activelot=1 group by cs_slots.id

如果一个人没有买很多,那么计数将为0。

如果您想要两个表中的所有记录,则不应使用group by:

select cs_lots.*, h.* from cs_lots left join cs_lots_history h on
cs_lots.id=h.id_lot and h.personaname='...' where cs_lots.activelot=1

这样,如果某个人没有出现在给定批次ID的历史记录表中,那么历史记录表中的列将为null。