连接mysql表并获取所有空记录


join mysql table and get all records if empty

我有3张表

venture - stores details about ventures
venture_buys - details about the venture purchases
users - details about the users

我使用下面的查询来连接所有3个表,并在一个块中显示详细信息

SELECT `a`.`user_id`, `a`.`g_id`,`b`.`first_name`, `b`.`last_name`,  `a`.`description`, `a`.`title`, `a`.`location`,b.title, sum(c.mt_qty) as m_qty
        FROM `users` `a`
        LEFT JOIN `venture` `b` ON `b`.`id`=`a`.`user_id`
        LEFT JOIN `venture_buys` `c` ON `c`.`g_id`=`a`.`g_id`
        ORDER BY `c`.`g_id` ASC

我遇到的问题是venture_buys只有在购买时才有详细信息,否则它总是空的。我用那张表来计算购买量。当我尝试添加和显示风险时,它不会显示记录,除非venture_buys有记录。

是否有办法改变查询或写一个条件,以获得所有的记录,即使没有记录在venture_buy?

在结构上做了很多假设,也许这就是你想做的:

SELECT `a`.`user_id`, `a`.`g_id`,`b`.`first_name`, `b`.`last_name`,  `a`.`description`, `a`.`title`, `a`.`location`,`b`.`title`, `c`.`sum_qty` as m_qty
        FROM `users` `a`
        LEFT JOIN `venture` `b` ON `b`.`id`=`a`.`user_id`
        LEFT JOIN (SELECT `g_id`,sum(`mt_qty`) AS `sum_qty` FROM `venture_buys` GROUP BY `g_id`) AS `c` ON `c`.`g_id`=`a`.`g_id`
        ORDER BY `c`.`g_id` ASC

不知道为什么我跟着那些不合逻辑的别名…

你可以试试这个,伙计:

SELECT
    u.user_id, u.g_id,
    v.first_name, v.last_name,
    u.description, u.title, u.location,
    v.title, SUM(vb.mt_qty) AS m_qty
FROM
    venture v
    INNER JOIN users u ON u.id = v.id
    INNER JOIN venture_buys ON vb.g_id = u.g_id
GROUP BY
    vb.g_id
ORDER BY
    vb.g_id ASC;