使用group by对多个表进行MySql查询

时间:2016-07-02 03:13:20

标签: mysql

我有4个表,如下所述,我正在尝试获取所有拍品中的所有拍品,而我在拍卖地块表中获得所有记录。

下面还给出了我尝试的查询以及正在使用的db结构。

Auctions (id, name)

id | name
-----------
1 | auction1
2 | auction2


Auction_lots (id, name, auction_id)

id | name | auction_id
---------------------------------
1 | lot1 | 2
2 | lot2 | 2
3 | lot3 | 2
4 | lot4 | 2
5 | lot5 | 2


Bids (id, user_id, auction_id, lot_id)

id | user_id | auction_id | lot_id
--------------------------------------------
1 |   1    |    2      |  5
2 |   1    |    2      |  3
3 |   1    |    2      |  1
4 |   1    |    2      |  2


Users(id, name)

id | name
-----------
1 | user1
2 | user2

我需要所有auction_lots,其中用户使用拍卖名称,批次名称和用户详细信息进行出价

我试过

    select PB.*, U.*, A.name as auc_name, AL.name as lot_name
    from auctions as A INNER JOIN
        auction_lots as AL
        ON A.id = AL.auction_id RIGHT JOIN
        phone_bids as PB
        ON AL.auction_id = PB.auction_id INNER JOIN
        users as U
        ON PB.user_id = U.id
    WHERE U.id =".$user_id."
    GROUP BY lot_name

在获得所有拍品时我只需要很多出价表

1 个答案:

答案 0 :(得分:0)

通过你获得你想要的东西

来删除正确的联合和分组
select 
        PB.*, U.*, A.name as auc_name, AL.name as lot_name

    from
        auctions as A

    INNER JOIN
        auction_lots as AL
        ON
        A.id = AL.auction_id

   INNER JOIN
        phone_bids as PB
        ON
        AL.auction_id = PB.auction_id

    INNER JOIN
        users as U
        ON
        PB.user_id =U.id
    WHERE
        U.id =".$user_id."