![](/img/trans.png)
[英]Mysql table join records from 2 tables but get all records even the ones with empty fields
[英]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
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;
對結構做了很多假設,也許這就是你想要做的:
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
不知道為什么我跟着那些不合邏輯的別名......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.