简体   繁体   English

加入mysql表并在为空时获取所有记录

[英]join mysql table and get all records if empty

im having 3 tables我有 3 张桌子

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

im using the below query to join all the 3 tables and show the details in a block我使用以下查询连接所有 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

the problem that im having is venture_buys has details only if its been purchased or else its always empty.我遇到的问题是 Venture_buys 只有在购买或始终为空时才具有详细信息。 i use that table to calculate the purchased quantity.我用那个表来计算购买的数量。 when i try to add and show the ventures it does not show the record unless venture_buys has a record.当我尝试添加和显示企业时,它不会显示记录,除非 Venture_buys 有记录。

is there way to change the query or write a condition to get all the records even if there is no record in venture_buy?即使 Venture_buy 中没有记录,有没有办法更改查询或编写条件以获取所有记录?

You can try this, mate:你可以试试这个,伙计:

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; 

Making a lot of assumptions on the structure, maybe this is what you want to do:对结构做了很多假设,也许这就是你想要做的:

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

Don't know why I followed those illogical allias names...不知道为什么我跟着那些不合逻辑的别名......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM